Entity Framework: field of composite key cannot be nullable?

天大地大妈咪最大 提交于 2019-12-17 19:33:25

问题


I have a model with composite key - the row is the key:

public class Item
{
    [Key, Column(Order = 0)]
    public int UserId { get; set; }
    [Key, Column(Order = 1)]
    public DateTime? Date { get; set; }
}

Running the code below it throws an exception DbEntityValidationException with message: The Date field is required.:

var it = new Item { Date = null, UserId = 2 };
m_Entities.Items.Add(it);
m_Entities.SaveChanges(); // throws exception

(m_Entities is usual DbContext descendant with Items defined as DbSet<Item>) Why is the Date required if it can be null (declared as DateTime?) ? And how to allow null to be a valid value for Date?


回答1:


Answer from Raphael lead me to another search. Here is the why it is not possible (answer from Cobsy):

What's wrong with nullable columns in composite primary keys?

In short: NULL == NULL -> false

Wierd. The solution for me is to add Id column into Model.

BTW: MySQL allow me not to define Primary Key, then I'm allowed to have such schema - EF complains about not defining the key :-(.




回答2:


It's not possible with Sql Server, or Oracle for any part of a primary key.

But you can have a unique constraint on these datas.

Which means you can have one time

UserId = 2, Date = null

Then

UserId = 2, Date = <NOT NULL>

You can't create directly unique constraints with Code First, but look at SMO.




回答3:


It is not possible. Every RDBMS requirement is, that primary key must be not nullable.



来源:https://stackoverflow.com/questions/10888087/entity-framework-field-of-composite-key-cannot-be-nullable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!