Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

c# - Entity Framework: field of composite key cannot be nullable?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 :-(.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...