实体框架:复合键的字段不能可空? [英] 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; }
}
运行code低于它抛出一个异常 DbEntityValidationException
与消息:是必需的日期字段
var it = new Item { Date = null, UserId = 2 };
m_Entities.Items.Add(it);
m_Entities.SaveChanges(); // throws exception
( m_Entities
是平时的DbContext
后代被定义为项目 DbSet<项目>
)
为什么日期
如果能够空
(声明为的DateTime?$所需C $ C>)?而如何让
空
来为日期有效值
?
(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
?
推荐答案
从拉斐尔回答使我另一个搜索。这里是为什么它是不可能的(从Cobsy回答):
Answer from Raphael lead me to another search. Here is the why it is not possible (answer from Cobsy):
<一个href=\"http://stackoverflow.com/questions/386040/whats-wrong-with-nullable-columns-in-composite-primary-keys\">What's错在复合主键空列?
在短期: NULL == NULL
- >假
奇怪。对我来说,解决方案是增加Id列到模型。
Wierd. The solution for me is to add Id column into Model.
BTW:MySQL的让我无法定义主键,然后我被允许有这样的模式 - EF抱怨没有定义键: - (
BTW: MySQL allow me not to define Primary Key, then I'm allowed to have such schema - EF complains about not defining the key :-(.
这篇关于实体框架:复合键的字段不能可空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!