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

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


Keys (primary)

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

约定

依照约定,一个名称为 Id 或者 <type name>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; }
}

Fluent API

我们也可以使用 Fluent API 来配置一个属性,使之成为主键。

class MyContext : DbContext
{
    public DbSet<Car> 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<Car> 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; }
}

转载于:https://www.cnblogs.com/JacZhu/p/5734852.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值