[英]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.
运行下面的代码会抛出异常
DbEntityValidationException
并带有消息: 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?
) ? (
m_Entities
通常是DbContext
后代,项目定义为DbSet<Item>
)如果Date
可以为null
(声明为DateTime?
),为什么需要Date
? And how to allow null
to be a valid value for Date
? 以及如何允许
null
成为Date
的有效值?
Answer from Raphael lead me to another search. Raphael的回答引导我进行另一次搜索。 Here is the why it is not possible (answer from Cobsy):
这就是为什么它不可能(Cobsy回答):
What's wrong with nullable columns in composite primary keys? 复合主键中可为空的列有什么问题?
In short: NULL == NULL
-> false 简而言之:
NULL == NULL
- > false
Wierd. 奇怪的。 The solution for me is to add Id column into Model.
我的解决方案是将Id列添加到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 :-(. BTW:MySQL的让我无法定义主键,然后我被允许有这样的模式 - EF抱怨没有定义键:-(。
It's not possible with Sql Server, or Oracle for any part of a primary key. 对于主键的任何部分,使用Sql Server或Oracle是不可能的。
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. 您无法使用Code First直接创建唯一约束,但请查看SMO。
It is not possible. 这不可能。 Every RDBMS requirement is, that primary key must be not nullable.
每个RDBMS要求是,主键必须不可为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.