【问题标题】:Entity Framework Core Many to Many change navigation property namesEntity Framework Core 多对多更改导航属性名称
【发布时间】: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"));

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

这是所有数据库优先。我不想为多对多表使用一个类,因为我在我的项目中完成了这一切,我不希望一堆无用的类四处飘荡。有什么想法吗?

【问题讨论】:

  • 如果您指定的列名与 EF 按约定使用的列名相同(忽略大小写),似乎会发生这种情况。在 SQL Server 中,这会抛出,因为对象名称应该是唯一的,而与大小写无关。您似乎有一个名称区分大小写的数据库。只需尝试使用 f.e. 会发生什么。 FK 名称中的“_Id”。
  • 是的,我使用的是 PostgreSQL,我认为它通常不区分大小写,但我们以区分大小写的方式使用它。

标签: c# postgresql entity-framework-core ef-core-5.0


【解决方案1】:

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

当相关实体 PK 属性称为 ID 时,它适用于除 {RelatedEntity}Id 之外的任何其他 FK 属性名称。

作为解决方法,直到它得到修复,配置关系之前明确定义所需的连接实体属性:


// 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 中得到修复。我原来的解决方案现在有效。
猜你喜欢
  • 2017-09-30
  • 2020-06-27
  • 2017-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2014-12-21
  • 1970-01-01
  • 2021-05-17
相关资源
最近更新 更多