使用实体框架的唯一主键

时间:2018-11-20 08:24:09

标签: c# sql .net entity-framework primary-key

我是EF的新手。假设我在数据库中有一个这样的表:

ID    FirstName     LastName    DateOfBirth
-------------------------------------------
1     John          Smith       1.1.1990
2     Mary          Wilson      5.1.1991

现在,我使用EF将新实体插入表中

dbcontext.Persons.Add(new Person
{
    FirstName = "John",
    LastName = "Smith",
    DateOfBith = "1.1.1990"
});
dbcontext.SaveChanges();

我需要代码引发异常,因为该行已经存在于数据库中,但是EF所做的是将ID列增加1并创建新记录:

ID    FirstName     LastName    DateOfBirth
--------------------------------------------
1     John          Smith       1.1.1990
2     Mary          Wilson      5.1.1991
3     John          Smith       1.1.1990

EF甚至有能力做到这一点吗?

2 个答案:

答案 0 :(得分:4)

您已经将ID列定义为identity column,并且该列已被视为您的主键,并且每次在表中插入新记录时都会增加一。这就是为什么允许您插入重复的实体。您需要在模型中(如果您使用代码优先方法)或通过使用Data Annotation,来指定需要声明为PK的列,如下所示:

[Key]
public string FirstName { get; set; }

或通过使用唯一约束:

[Index("IX_UniqueConstraint", 1, IsUnique = true)]
public string FirstName { get; set; }

[Index("IX_UniqueConstraint", 2, IsUnique = true)]
public string LastName { get; set; }

[Index("IX_UniqueConstraint", 3, IsUnique = true)]
public DateTime DateOfBirth { get; set; }

您也可以为此使用fluent API

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Persons>().HasKey(c => new { c.FirstName, c.LastName, c.DateOfBirth });
}

或者,如果您使用的是数据库优先方式,则可以在数据库中声明它。

答案 1 :(得分:2)

使用EF,您需要执行以下操作:

[Index("IX_UniqueConstraint", 1, IsUnique = true)]
public string FirstName { get; set; }

[Index("IX_UniqueConstraint", 2, IsUnique = true)]
public string LastName { get; set; }

[Index("IX_UniqueConstraint", 3, IsUnique = true)]
public DateTime DateOfBirth { get; set; }

这将在3列上施加唯一约束。

相关问题