【发布时间】:2018-07-12 14:28:24
【问题描述】:
我有以下实体:
public class Level
{
public int LevelId { get; set; }
public int? ParentLevelId { get; set; }
public string Name { get; set; }
public virtual Level Parent { get; set; }
public virtual HashSet<Level> Children { get; set; }
}
我在这里遇到的问题是 Children 属性,它在 Fluent API 中是这样配置的:
modelBuilder.Entity<Level>()
.HasOne(x => x.Parent)
.WithMany(x => x.Children)
.HasForeignKey(x => x.ParentLevelId);
这会导致迁移添加了一些额外的列:
migrationBuilder.AddColumn<int>(
name: "LevelId1",
table: "Level",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Level_LevelId1",
table: "Level",
column: "LevelId1");
migrationBuilder.AddForeignKey(
name: "FK_Level_Level_LevelId1",
table: "Level",
column: "LevelId1",
principalTable: "Level",
principalColumn: "LevelId",
onDelete: ReferentialAction.Restrict);
我在这里做错了什么?
编辑:问题被标记为可能与this question 重复;但是,在这种情况下,模型生成工作 - 问题是加载数据。而这里的问题是生成了一个额外的列。
【问题讨论】:
-
LevelId 是 PK 吗?如果是这样,请尝试在属性上方添加关键注释,例如:[Key] public int LevelId {get;set;}
-
这是所有代码还是为了简洁而省略了其他属性?
-
@dickrichie 刚刚尝试添加 [Key] 属性,同样的事情发生了。
-
@GertArnold 为简洁起见,我省略了其他内容。我还有一些字符串和 DateTime 属性,没什么复杂的。
标签: c# entity-framework-core one-to-many ef-fluent-api ef-core-2.1