我有一个名为“ LogBookSystemUsers”的表,我想在EF Core 5中设置许多功能。我几乎可以使用它,但是问题是我的ID列已命名SystemUserId
,LogBookId
但是当EF进行联接时,它会尝试使用SystemUserID
和LogBookID
。这是我当前的配置代码:
modelBuilder.Entity<SystemUser>()
.HasMany(x => x.LogBooks)
.WithMany(x => x.SystemUsers)
.UsingEntity(x =>
{
x.ToTable("LogBookSystemUsers", "LogBooks");
});
我尝试了这个:
modelBuilder.Entity<SystemUser>()
.HasMany(x => x.LogBooks)
.WithMany(x => x.SystemUsers)
.UsingEntity<Dictionary<string, object>>("LogBookSystemUsers",
x => x.HasOne<LogBook>().WithMany().HasForeignKey("LogBookId"),
x => x.HasOne<SystemUser>().WithMany().HasForeignKey("SystemUserId"),
x => x.ToTable("LogBookSystemUsers", "LogBooks"));
但这只是添加了两个新列,而不是设置当前列的名称。
这首先是所有数据库。我不想为多对多表使用一个类,因为我在项目中都这样做了,而且我也不想一堆堆无用的类。有任何想法吗?
有趣的错误,请考虑将其发布到EF Core GitHub问题跟踪器。
根据想法,你尝试过的应该做
modelBuilder.Entity<SystemUser>()
.HasMany(x => x.LogBooks)
.WithMany(x => x.SystemUsers)
.UsingEntity<Dictionary<string, object>>("LogBookSystemUsers",
x => x.HasOne<LogBook>().WithMany().HasForeignKey("LogBookId"),
x => x.HasOne<SystemUser>().WithMany().HasForeignKey("SystemUserId"),
x => x.ToTable("LogBookSystemUsers", "LogBooks"));
它适用于任何其他FK属性名称,但{RelatedEntity}Id
调用关联实体PK属性的时间除外ID
。
作为解决方法,直到它得到解决,在配置关系之前,先明确定义所需的联接实体属性:
// add this
modelBuilder.SharedTypeEntity<Dictionary<string, object>>("LogBookSystemUsers", builder =>
{
builder.Property<int>("LogBookId");
builder.Property<int>("SystemUserId");
});
// same as the original
modelBuilder.Entity<SystemUser>()
.HasMany(x => x.LogBooks)
.WithMany(x => x.SystemUsers)
.UsingEntity<Dictionary<string, object>>("LogBookSystemUsers",
x => x.HasOne<LogBook>().WithMany().HasForeignKey("LogBookId"),
x => x.HasOne<SystemUser>().WithMany().HasForeignKey("SystemUserId"),
x => x.ToTable("LogBookSystemUsers", "LogBooks"));
谢谢!效果很好,只是告诉我我需要一个钥匙,所以我必须添加一个钥匙:
builder.HasKey("LogBookId", "SystemUserId");
EF Core 5.0.2版中已修复此问题。我原来的解决方案现在可以正常工作了。