我正在将 EF Core 与 MySQL 结合使用,使用 SapientGuardian's EFCore library我正在尝试使用以下代码创建一个具有多对多关系的表;
public class Personnel
{
public int Id { get; set; }
[MaxLength(100)]
public string Name { get; set; }
public virtual ICollection<PersonnelDegree> PersonnelDegrees { get; set; }
}
public class Degree
{
public int Id { get; set; }
[MaxLength(100)]
public string Name { get; set; }
public virtual ICollection<PersonnelDegree> PersonnelDegrees { get; set; }
}
public class PersonnelDegree
{
public int PersonnelId { get; set; }
public int DegreeId { get; set; }
public virtual Personnel Personnel { get; set; }
public virtual Degree Degree { get; set; }
}
// Inside the OnModelCreating override
builder.Entity<Degree>().HasMany(x => x.Personnel);
builder.Entity<Personnel>().HasMany(x => x.Degrees);
builder.Entity<PersonnelDegree>()
.HasKey(x => new { x.DegreeId, x.PersonnelId });
builder.Entity<PersonnelDegree>()
.HasOne(x => x.Degree)
.WithMany(x => x.PersonnelDegrees)
.HasForeignKey(x => x.DegreeId);
builder.Entity<PersonnelDegree>()
.HasOne(x => x.Personnel)
.WithMany(x => x.PersonnelDegrees)
.HasForeignKey(x => x.PersonnelId);
现在,当我运行 dotnet ef 迁移时添加人员;我明白了...
migrationBuilder.CreateTable(
name: "Role",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("MySQL:AutoIncrement", true),
ApplicationId = table.Column<int>(nullable: true),
Name = table.Column<string>(maxLength: 100, nullable: true),
PersonnelId = table.Column<int>(nullable: true) // Where is this coming from?
},
constraints: table =>
{
table.PrimaryKey("PK_Role", x => x.Id);
table.ForeignKey(
name: "FK_Role_Application_ApplicationId",
column: x => x.ApplicationId,
principalTable: "Application",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
请注意,角色的表定义中有 PersonnelId 列。人员表有 RoleId 吗?谁能告诉我这是怎么回事?
最佳答案
我有相同的模型,但 OnModelCreating 方法不同。
所以我假设您配置错误。对于您的情况应该是这样的:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<PersonnelDegree>()
.HasKey(t => new { t.PersonnelId , t.DegreeId });
}
这就是您的 OnModelCreating 方法中应该拥有的全部内容。
关于mysql - MySql 中多对多关系的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40294727/