C# 如何配置EF以自动填充子外键
当父类未使用数据库生成的标识符时,如何配置Entity Framework以自动填充子对象中的外键 示例模型:C# 如何配置EF以自动填充子外键,c#,entity-framework,ef-code-first,C#,Entity Framework,Ef Code First,当父类未使用数据库生成的标识符时,如何配置Entity Framework以自动填充子对象中的外键 示例模型: public class Parent { [Key] public string Name { get; set; } public virtual List<Child> Children { get; set; } } public class Child { [Key] [Column(Order = 1)] pu
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; }
}
您可以将导航属性添加到子类,配置模型,然后一切都应该正常工作
public class Child
{
[Key]
[Column(Order = 1)]
public string ParentName { get; set; }
[Key]
[Column(Order = 2)]
public string ChildName { get; set; }
public virtual Parent Parent { get; set; } // <-- Add this
}
公共类子类
{
[关键]
[第列(顺序=1)]
公共字符串ParentName{get;set;}
[关键]
[第列(顺序=2)]
公共字符串ChildName{get;set;}
公共虚拟父级(父级{get;set;}//\u0.Children)
.WithRequired(\u=>\ u0.Parent)
.HasForeignKey(=>.ParentName);
(没有孩子,父母不管用,行为很奇怪)为什么不能将关系配置为FK?@Sampath根据约定,FK已配置。我添加了迁移以显示其已配置。我只是想知道,当我将项目添加到父子列表时,FK ParentName是否可以自动由EF填充。相关的,可能的重复:谢谢@bubi,我只需要添加虚拟导航初始化属性。不需要该配置。在我的情况下,我不需要导航属性,所以我没有导航属性。EF在重写和设置Child.Parent导航属性时必须填充ParentName属性。我总是添加配置。我害怕EF更新:)
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);
public class Child
{
[Key]
[Column(Order = 1)]
public string ParentName { get; set; }
[Key]
[Column(Order = 2)]
public string ChildName { get; set; }
public virtual Parent Parent { get; set; } // <-- Add this
}
modelBuilder.Entity<Parent>()
.HasMany(_ => _.Children)
.WithRequired(_ => _.Parent)
.HasForeignKey(_ => _.ParentName);