Warm tip: This article is reproduced from serverfault.com, please click

c#- Entity framework 核心多对多更改导航属性名称

(c# - Entity Framework Core Many to Many change navigation property names)

发布于 2020-11-27 21:15:43

我有一个名为“ LogBookSystemUsers”的表,我想在EF Core 5中设置许多功能。我几乎可以使用它,但是问题是我的ID列已命名SystemUserIdLogBookId但是当EF进行联接时,它会尝试使用SystemUserIDLogBookID这是我当前的配置代码:

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"));

但这只是添加了两个新列,而不是设置当前列的名称。

这首先是所有数据库。我不想为多对多表使用一个类,因为我在项目中都这样做了,而且我也不想一堆堆无用的类。有任何想法吗?

Questioner
GBreen12
Viewed
11
Ivan Stoev 2020-11-28 11:55:57

有趣的错误,请考虑将其发布到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"));