【问题标题】:Entity Framework Core 5: configuring many to many relationships, how to specify foreign key namesEntity Framework Core 5:配置多对多关系,如何指定外键名
【发布时间】:2021-05-08 12:42:32
【问题描述】:

我有一个现有的 SQL Server 数据库,它具有多对多关系 Books Authors 通过连接表实现 Publications:

CREATE TABLE [dbo].[Books]
(
    [BookId] INT IDENTITY,
    [Title] NVARCHAR(160) NOT NULL,
    ...
)

CREATE TABLE [dbo].[Authors]
(
    [AuthorId] INT IDENTITY,
    ...
)

CREATE TABLE [dbo].[Publications]
(
    [BookId] INT NOT NULL,
    [AuthorId] INT NOT NULL,

    CONSTRAINT [PK_Publication] PRIMARY KEY ([BookId], [AuthorId])
)

我需要在 Entity Framework Core 5 中配置多对多关系。

使用 EF 6,这相当简单:

protected override void OnModelCreating(DbModelBuilder mb)
{
    mb.Entity<Author>() // an Author
         .HasMany(a => a.Books) // has many Books
         .WithMany(b => b.Authors) // with many Authors
         .Map(mc =>
               {
                    mc.ToTable("Publications"); // Join table: Publications
                    mc.MapLeftKey("AuthorId"); // FK Author: AuthorId
                    mc.MapRightKey("BookId"); // FK Book : BookId
               });
}

但我在使用 Entity Framework Core 5 时遇到问题:

protected override void OnModelCreating(ModelBuilder mb)
{
    mb.Entity<Author>() // an Author
          .HasMany(a => a.Books) // has many Books
          .WithMany(b => b.Authors) // with many Authors
          .UsingEntity(j => j.ToTable("Publications")); // join table: Publications
          // how to define foreign key columns?
}

我不知道如何映射外键列。 EF Core 5 使用AuthorsAuthorIdBooksBookId 模式。

如何更改此命名约定?

谢谢

【问题讨论】:

    标签: c# database entity-framework-core .net-5


    【解决方案1】:

    如果多对多表在 C# 代码中不相关,您可以试试这个:

    public class Author
    {
       public int AuthorId { get; set; }
       public ICollection<Book> Books { get; set; }
    }
    public class Book
    {
       public int BookId { get; set; }
       public ICollection<Author> Authors { get; set; }
    }
    public class Db : DbContext
    {
       protected override void OnModelCreating(ModelBuilder mb)
       {
          mb.Entity<Author>() // an Author
          .HasMany(a => a.Books) // has many Books
          .WithMany(b => b.Authors) // with many Authors
          .UsingEntity<Dictionary<string, object>>("Publications",
            x => x.HasOne<Book>().WithMany().HasForeignKey(nameof(Book.BookId)),
            y => y.HasOne<Author>().WithMany().HasForeignKey(nameof(Author.AuthorId)),
            z => z.ToTable("Publications"));
       }
    }
    

    【讨论】:

    • 非常好,很高兴它有帮助。您能否将我的答案标记为完整?谢谢
    • 我想赞成这个答案,但它使用糟糕的命名来解释更精细的点。在这些情况下,xyz 是什么?不要使用单个字母的名称来期望人们只是神奇地弄清楚他们的真实身份。
    • 大卫,是的,谢谢你在命名 x 上是正确的,y 应该重命名。尽管说“期望人们只是神奇地弄清楚他们的真实身份”,但最好将其表述为“请重命名,这样意图就很明确了”,但您肯定会同意居高临下的意义不大。我们在这里互相帮助 :-) 谢谢
    猜你喜欢
    • 2019-06-18
    • 2021-04-09
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 2021-07-31
    相关资源
    最近更新 更多