zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Linux脚本文件注释
    Linux三剑客之grep命令
    Linux获取本机IP
    Linux的cut命令详解
    Linux的wc命令详解
    Linux的uniq命令详解
    Linux的sort命令详解
    shell之a+b求和脚本的三种写法
    shell的文件比较运算符和字符串比较运算符
    shell中变量$系列的含义
  • 原文地址:https://www.cnblogs.com/JacZhu/p/5734852.html
Copyright © 2011-2022 走看看