实体框架:复合键的字段不能为空? [英] Entity Framework: field of composite key cannot be nullable?

查看:113
本文介绍了实体框架:复合键的字段不能为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

运行下面的代码会抛出异常 DbEntityValidationException 与消息:日期字段是必需的。

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

m_Entities DbContext 后代,项目定义为 DbSet< Item>
为什么如果可以 null (声明为 DateTime?),则需要日期而如何允许 null 成为 Date 的有效值?

解决方案

从拉斐尔的回答引导我进行另一个搜索。以下是为什么不可能(Cobsy的答案):



复合主键中的可空列有什么问题?



简而言之:
NULL == NULL - > false



Wierd。我的解决方案是将Id列添加到Model中。



BTW:MySQL允许我不定义主键,那么我被允许有这样的模式 - EF投诉关于不定义密钥: - (。


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?

解决方案

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

这篇关于实体框架:复合键的字段不能为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆