Entity Framework Core 实体关系的配置

Posted JimCarter

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Entity Framework Core 实体关系的配置相关的知识,希望对你有一定的参考价值。

https://docs.microsoft.com/zh-cn/ef/core/modeling/relationships

1. 术语介绍

  • Dependent entity: 依赖实体(子实体),包含外键的实体,实体关系中的子。
  • Principal entity: 主体实体(父实体),包含主键/备用键的实体,实体关系中的父。
  • Principal key: 主键/备用键
  • Foreign key: 外键
  • Navigation property: 导航属性,出现在父实体或主实体中,用来维系两个实体间的关系。
    • Collection navigation property:集合导航,是一个ICollection<T>
    • Reference navigation property:引用导航,是一个T
    • Inverse navigation property:反向导航属性
  • Self-referencing relationship:自引用的关系,如树形结构中的id和parentId

参考以下代码:

public class Blog//父实体
{
    public int BlogId { get; set; }//主键
    public string Url { get; set; }

    public ICollection<Post> Posts { get; set; }//导航属性,也是Post.Blog的反向导航属性
}

public class Post//子实体
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }//外键
    public Blog Blog { get; set; }//导航属性,也是Blog.Posts的反向导航属性
}

2. 关系自动配置

如果实体类的一个属性无法映射为标量类型(scalar type), 如int、long等,则认为它就是导航属性。
如果在某个实体类上发现了导航属性,将会创建一个关系。

2.1 完整配置

如上一小节的PostBlog的关系,定义比较完备。定义完备有两点要求:

  • 实体两边有对应的导航属性,而非一边有一边没有
  • 如果“子实体”中某个属性的名称符合以下规则(即外键的命名规则),则被配置为外键:
    • <navigation property name><principal key property name>
    • <navigation property name>Id
    • <principal entity name><principal key property name>
    • <principal entity name>Id

2.2 无外键情况下进行配置

虽然建议要有外键,但是没有外键也ok。当没外键时会引入名称符合<navigation property name><principal key property name><principal entity name><principal key property name>规则的影子属性作为外键。

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    
    public ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    
    public Blog Blog { get; set; }
}

此时会产生一个名为BlogId的影子属性。注意:这个BlogId仍然会出现在数据库中,且是可空类型

2.3 无“导航属性对”情况下配置

即使没有对应的反向导航属性,没有外键属性,但只要存在一个导航属性就能建立起关系

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

3. 关系手动配置

使用HasOne/HasMany配置导航属性,使用WithOne/WithMany配置反向导航属性。

internal class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>()
            .HasOne(p => p.Blog)//表示一个Post对应一个Blog
            .WithMany(b => b.Posts);//表示一个Blog对应多个Post
            
        //上述代码等效于下面这两行
        modelBuilder.Entity<Post>().HasOne(p=>p.Blog);
        modelBuilder.Entity<Blog>().HasMany(b=>b.Posts);
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public Blog Blog { get; set; }
}

当然也可以通过特性配置:

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int AuthorUserId { get; set; }
    public User Author { get; set; }

    public int ContributorUserId { get; set; }
    public User Contributor { get; set; }
}

public class User
{
    public string UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [InverseProperty("Author")]
    public ICollection<Post> AuthoredPosts { get; set; }

    [InverseProperty("Contributor")]
    public ICollection<Post> ContributedToPosts { get; set; }
}

看下建表语句都是什么:

CREATE TABLE "SysRole" (
    "Id" INTEGER NOT NULL CONSTRAINT "PK_SysRole" PRIMARY KEY AUTOINCREMENT,
    "RoleName" TEXT NOT NULL
);

CREATE TABLE "SysUsers" (
    "Id" INTEGER NOT NULL CONSTRAINT "PK_SysUsers" PRIMARY KEY AUTOINCREMENT,
    "UserName" TEXT NOT NULL,
    "Pwd" TEXT NOT NULL,
    "CreateTime" TEXT NULL,
    "RoleId" INTEGER NULL,
    CONSTRAINT "FK_SysUsers_SysRole_RoleId" FOREIGN KEY ("RoleId") REFERENCES "SysRole" ("Id") ON DELETE RESTRICT
);

3.1 无“导航属性对”时手动配置

如果你的导航属性不是成对的,则WithOneWithMany可以不传入参数。

internal class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .HasMany(b => b.Posts)
            .WithOne();
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

3.2 手动指定外键

使用FluentAPI可以配置单一外键和复合外键:
单一外键:

internal class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>()
            .HasOne(p => p.Blog)
            .WithMany(b => b.Posts)
            .HasForeignKey(p => p.BlogForeignKey);
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogForeignKey { get; set; }
    public Blog Blog { get; set; }
}

复合外键:

internal 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 });//复合主键

        modelBuilder.Entity<RecordOfSale>()
            .HasOne(s => s.Car)
            .WithMany(c => c.SaleHistory)
            .HasForeignKey(s => new { s.CarState, s.CarLicensePlate });//复合外键
    }
}

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

    public ICollection<RecordOfSale> SaleHistory { get; set; }
}

public class RecordOfSale
{
    public int RecordOfSaleId { get; set; }
    public DateTime DateSold { get; set; }
    public decimal Price { get; set; }

    public string CarState { get; set; }
    public string CarLicensePlate { get; set; }
    public Car Car { get; set; }
}

除了FluentAPI外,也可以使用特性配置单一外键:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogForeignKey { get; set; }

    [ForeignKey("BlogForeignKey")]//如果BlogForeignKey不存在,则会创建影子属性
    public Blog Blog { get; set; }
}

配置影子外键:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
        //1.首先配置影子属性
        modelBuilder.Entity<Post>()
            .Property<int>("BlogForeignKey");

        //2.然后将影子属性配置成外键
        modelBuilder.Entity<Post>()
            .HasOne(p => p.Blog)
            .WithMany(b => b.Posts)
            .HasForeignKey("BlogForeignKey");
}

配置外键的名称:默认情况下外键约束的名称规则为FK _<依赖实体的类名>_<主体实体的类名>_<外键属性的名称>。在数据库中可以看到实际的名称,如FK_SysUsers_SysRole_RoleId
当然也可以手动更改外键约束的名称:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Post>()
        .HasOne(p => p.Blog)
        .WithMany(b => b.Posts)
        .HasForeignKey(p => p.BlogId)
        .HasConstraintName("ForeignKey_Post_Blog");
}

3.3 无导航属性时手动配置

internal class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>()
            .HasOne<Blog>()
            .WithMany()
            .HasForeignKey(p => p.BlogId);
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

public class Post
{
    以上是关于Entity Framework Core 实体关系的配置的主要内容,如果未能解决你的问题,请参考以下文章

Entity Framework Core中更改跟踪工作原理

Entity Framework Core中更改跟踪工作原理

如何将动态实体设置为 dbcontext Entity Framework Core?

什么是自有实体?何时以及为什么在 Entity Framework Core 中使用 Owned Entity?

Entity Framework Core - 如何处理相关实体映射和保存

更新 ASP.NET Core Entity Framework 中的实体类