【发布时间】:2016-09-08 14:49:36
【问题描述】:
当父类不使用数据库生成的标识符时,如何配置实体框架以自动填充子对象中的外键。
示例模型:
public class Parent
{
[Key]
public string Name { get; set; }
public virtual List<Child> Children { get; set; }
}
public class Child
{
[Key]
[Column(Order = 1)]
public string ParentName { get; set; }
[Key]
[Column(Order = 2)]
public string ChildName { get; set; }
}
示例种子方法:
context.Parents.AddOrUpdate(p => p.Name,
new Parent
{
Name = "Test",
Children = new List<Child>
{
new Child {ParentName = "Test", ChildName = "TestChild"},
new Child {ParentName = "Test", ChildName = "NewChild"}
}
});
是否可以配置 EF,以便我不必为子列表中的每个新子手动设置 ParentName = "Test"?
编辑 - 这是生成的迁移
CreateTable(
"dbo.Parents",
c => new
{
Name = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => t.Name);
CreateTable(
"dbo.Children",
c => new
{
ParentName = c.String(nullable: false, maxLength: 128),
ChildName = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new {t.ParentName, t.ChildName})
.ForeignKey("dbo.Parents", t => t.ParentName, cascadeDelete: true)
.Index(t => t.ParentName);
【问题讨论】:
-
为什么不能将关系配置为FK?
-
@Sampath 按照惯例配置了 FK。我添加了迁移以显示它正在配置。我只是想知道当我将项目添加到父子列表时,EF 是否可以自动填充 FK ParentName。
标签: c# entity-framework ef-code-first