【发布时间】: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 使用AuthorsAuthorId 和BooksBookId 模式。
如何更改此命名约定?
谢谢
【问题讨论】:
标签: c# database entity-framework-core .net-5