gpt4 book ai didi

c# - Entity Framework Core 5 : configuring many to many relationships, 如何指定外键名称

转载 作者:行者123 更新时间:2023-12-03 08:22:31 26 4
gpt4 key购买 nike

我有一个现有的 SQL Server 数据库,其中通过连接表 Publications 实现了多对多关系 Books <-> Authors:

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# 代码中不相关,您可以尝试此操作:

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

关于c# - Entity Framework Core 5 : configuring many to many relationships, 如何指定外键名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67447691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com