简体   繁体   English

实体框架IsUnique并接受Null

[英]Entity Framework IsUnique and accept Nulls

How can I make a Code First property that accepts null values but it's also an [Index(IsUnique=true)] ? 我怎样才能使Code First属性接受空值,但它也是[Index(IsUnique=true)]

For example: a passport number should't be repeated, ergo the IsUnique , but if the user doesn't insert one, then it defaults to null, so it accepts multiple nulls. 例如:护照号码不应该重复, IsUnique ,但是如果用户不输入护照号码,则默认为null,因此可以接受多个null。

Since it will not be unique then, you cannot do it that way. 由于它不是唯一的,所以您不能那样做。 But you can manage it, by attaching a table: 但是您可以通过附加表来管理它:

public class Person {
    public int Id { get; set; }
}

public class Passport {
    [Key]
    public int PersonId { get; set; }
    [ForeignKey("PersonId")]
    public Person Person { get; set; }
    [Index(IsUnique=true)]
    public string PassportId { get; set; }
}

Be aware, that there are countries, which do not allow storing such numbers. 请注意,有些国家不允许存储此类数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架错误:PredicateBuilder发生异常并比较null - Entity Framework Bug: Exception with PredicateBuilder and comparing nulls 实体框架“列不允许为空” - Entity Framework 'column does not allow nulls' 如何在Entity Framework中使用值和null的混合值执行特定顺序 - How to do a specific order by in Entity Framework with a mixture of values and nulls 使用实体框架填充一个组合框,以删除空值 - Using Entity Framework fill a combo box removing nulls C# LINQ 在搜索过程中忽略空值的实体框架查询 - C# LINQ Entity Framework query that ignores nulls as part of the search AcceptAllChanges导致实体框架......不接受更改? - AcceptAllChanges causes Entity Framework to … not accept the changes? 实体框架,如何使Sum &lt;&gt;接受方法? - Entity Framework, how to get Sum<> accept a method? 具有npgsql的实体框架将不接受money数据类型 - Entity Framework with npgsql won't accept money datatype 实体框架6 GUID作为主键:无法将值NULL插入表&#39;FileStore&#39;的列&#39;Id&#39;中; 列不允许为空 - Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls 为什么匿名类型实例不能接受实体框架查询返回的空值? - Why the anonymous type instance cannot accept null values returned by the entity framework query?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM