【发布时间】:2021-02-06 16:27:00
【问题描述】:
我有 Tag 和 Post 类(多对多关系,代码优先)
class Post {
ICollection<Tag> Tags {get; set;} = new List<Tag>();
}
class Tag {
ICollection<Post> Posts {get; set;} = new List<Post>();
}
Tag 和 Post 类具有对应的 Tag 和 Post 表和 TagId 和 PostId 主键(注意 singular 命名约定)
在配置我的Post 的构建器时,我说
builder
.HasMany(p => p.Tags)
.WithMany(p => p.Posts)
.UsingEntity(j => j.HasData(new { PostId = 1, TagId = 1 }));
当我向add-migration Initial 添加尝试时,一个阻塞错误会中断迁移创建:
实体类型 'PostTag (Dictionary
)',因为没有为 必需的属性“PostsId”。
有人能解释一下这条消息背后隐藏着什么吗?
我看到它通过 plurals (PostsId vs PostId),但我不想在外键上使用复数,有没有办法使用 PostId而不是PostsId?
.UsingEntity(j => j.HasData(new { PostsId = 1, TagsId = 1 }));
此外,它还会创建以下迁移:
migrationBuilder.CreateTable(
name: "PostTag (Dictionary<string, object>)",
columns: table => new
{
PostsId = table.Column<int>(type: "int", nullable: false),
TagsId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PostTag (Dictionary<string, object>)", x => new { x.PostsId, x.TagsId });
table.ForeignKey(
name: "FK_PostTag (Dictionary<string, object>)_Post_PostsId",
column: x => x.PostsId,
principalTable: "Post",
principalColumn: "PostId",
onDelete: ReferentialAction.Cascade);
表名“PostTag (Dictionary
使用这些约定的逻辑是什么?怎样才能有正常的PostTag 表名?
【问题讨论】:
-
想从选民那里结束这个问题,什么“堆栈溢出指南”不符合这个问题......
-
我之前没有使用过 UsingEntity。我通常在模型中显式地创建连接表。但是,您确定要在该配置中使用 HasData 而不是 HasKey?
标签: c# entity-framework-core ef-code-first ef-core-5.0