GBr*_*n12 8 c# postgresql entity-framework-core entity-framework-core-5
我有一个名为“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"));
| 归档时间: | 
 | 
| 查看次数: | 1685 次 | 
| 最近记录: |