EntityFramework Core 学习笔记 —— 添加主键约束

原文地址:[https://docs.efproject.net/en/latest/modeling/keys.html][1]


Keys (primary)

Key 是每个实体例的主要唯一标识。EF Core中的 Key 映射到关系型数据库中就相当于主键。我们也可以配置一个不是主键的唯一标识给一个实体。(点这里 [Alternate Keys][2] 查看更多信息)
内容导航

  • [约定][3]
  • [Data Annotation][4]
  • [Fluent API][5]

约定

依照约定,一个名称为 `Id` 或者 `Id` 的属性将会被配置为实体的 Key。
class Car
{
    public string Id { get; set; }    // 人工高亮

    public string Make { get; set; }
    public string Model { get; set; }
}
    class Car
    {
        public string CarId { get; set; }    // 人工高亮

        public string Make { get; set; }
        public string Model { get; set; }
    }

Data Annotations

我们也可以使用 Data Annotations 来配置一个属性,使之成为主键。 ``` class Car { [Key] // 人工高亮 public string LicensePlate { get; set; }
public string Make { get; set; }
public string Model { get; set; }

}


<h2 id="3">Fluent API</h2>
我们也可以使用 Fluent API 来配置一个属性,使之成为主键。

class MyContext : DbContext
{
public DbSet Cars { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Car>().HasKey(c => c.LicensePlate);    // 人工高亮
}

}

class Car
{
public string LicensePlate { get; set; }

public string Make { get; set; }
public string Model { get; set; }

}


当然了,我们也可以使用 Fluent API 来配置多个属性复合组成实体的 Key (在关系型数据库中,我们称之为复合主键)。**复合主键只能通过 Fluent API 设置,约定以及 Data Annotations 都无法设置复合主键。**

class MyContext : DbContext
{
public DbSet Cars { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Car>()
        .HasKey(c => new { c.State, c.LicensePlate });    // 人工高亮
}

}

class Car
{
public string State { get; set; }
public string LicensePlate { get; set; }

public string Make { get; set; }
public string Model { get; set; }

}


  [1]: https://docs.efproject.net/en/latest/modeling/keys.html
  [2]: #todo
  [3]: #1
  [4]: #2
  [5]: #3
posted @ 2016-08-03 22:39  不如隐茶去  阅读(1564)  评论(0编辑  收藏  举报