【发布时间】: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