【问题标题】:Many to many relationship with the same entity in Entity Framework CoreEntity Framework Core 中同一个实体的多对多关系
【发布时间】:2020-02-15 17:56:55
【问题描述】:

当我在两个类之间实现多对多关系,并使用 fluent api 配置其复合主键时,EF Core 不会在数据库中创建 2 列,而是创建 3 列。

UserReport.cs

public class UserReports
{
    public int ReporterId { get; set; }
    public User Reporter { get; set; }

    public int ReporteeId { get; set; }
    public User Reportee { get; set; }
}

User.cs

public class User: IdentityUser<int>
{
    public DateTime DateOfBirth { get; set; }
    public string KnownAs { get; set; }
    public DateTime Created { get; set; }
    public DateTime LastActive { get; set; }

    public ICollection<UserReports> Reporters { get; set; } = new Collection<UserReports>();
    public ICollection<UserReports> Reportees { get; set; } = new Collection<UserReports>();
}

ApplicatiobDbContext.cs

modelBuilder.Entity<UserReports>()
   .HasKey(ru => new { ru.ReporterId, ru.ReporteeId});

modelBuilder.Entity<UserReports>()
   .HasOne(ru => ru.Reportee)
   .WithMany(u => u.Reporters)
   .OnDelete(DeleteBehavior.Restrict);

modelBuilder.Entity<UserReports>()
   .HasOne(ru => ru.Reporter)
   .WithMany(u => u.Reportees)
   .OnDelete(DeleteBehavior.Restrict);

迁移

在添加迁移之后,EF 核心生成这种类型的迁移,这会创建一个额外的列

ReporterId1 = table.Column<int>(nullable: true)

migrationBuilder.CreateTable(
        name: "ReportUsers",
        columns: table => new
        {
           ReporterId = table.Column<int>(nullable: false),
           ReporteeId = table.Column<int>(nullable: false),
           ReporterId1 = table.Column<int>(nullable: true),
           Message = table.Column<string>(nullable: false)
        },

【问题讨论】:

    标签: c# asp.net-core entity-framework-core


    【解决方案1】:

    您在配置中没有提到HasForeignKey,这就是为什么映射外键时出现混淆的原因,因为它是many-to-many 与相同的实体。按如下方式更新您的配置:

    modelBuilder.Entity<UserReports>()
       .HasKey(ru => new { ru.ReporterId, ru.ReporteeId});
    
    modelBuilder.Entity<UserReports>()
       .HasOne(ru => ru.Reportee)
       .WithMany(u => u.Reporters)
       .HasForeignKey(ru => ru.ReporteeId); // <-- Here it is
       .OnDelete(DeleteBehavior.Restrict);
    
    modelBuilder.Entity<UserReports>()
       .HasOne(ru => ru.Reporter)
       .WithMany(u => u.Reportees)
       .HasForeignKey(ru => ru.ReporterId); // <-- Here it is
       .OnDelete(DeleteBehavior.Restrict);
    

    【讨论】:

    • @MalikHaseeb 很高兴听到您的问题已经解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 2020-12-09
    相关资源
    最近更新 更多