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
  • 相关阅读:
    Laravel Passport token过期后判断refresh_token是否过期
    js 数组随机排序
    jquery的animate关于background-position属性
    css hack 汇整
    顶部导航--向上滚动的时候出现,向下滚动的时候隐藏
    手机端全局样式表整理(mobile)
    AR专用汉明码
    css常用命名规则
    晚11点
    当 IDENTITY_INSERT 设置为 OFF 时,不能为表‘XXX’中的标识列插入显式值。
  • 原文地址:https://www.cnblogs.com/JacZhu/p/5734852.html
Copyright © 2011-2022 走看看