实体框架:保存新父级,不保存新子级

时间:2015-09-25 17:16:25

标签: c# entity-framework

我有以下课程:

public class ParentObject {
    [DatabaseGenerated(DatabaseGeneratedOption.Identity), Key]
    public int Id { get; set; }

    public string Name { get; set; }

    [ForeignKey("ParentId")]
    public List<ChildObject> ChildObjects { get; set; }
}

public class ChildObject {
    [DatabaseGenerated(DatabaseGeneratedOption.Identity), Key]
    public int Id { get; set; }

    public int ParentId { get; set; }

    public string Name { get; set; }
}

我有一种方法可以添加一个带有新子项的新父级:

private void Add(string parentName, string childName) {
    using (MyDbContext context = new MyDbContext ()) {
        ParentObject newParent = new ParentObject { Name = parentName };
        ChildObject newChild = new ChildObject { Name = childName };
        newParent.ChildObjects = new List< ChildObject> { newChild };    
        context.ParentObjects.Add(newParent);
        context.SaveChanges();
    }
}

父级保存到数据库,但子级不保存。我的理解是,拥有外键约束应该将所有内容绑定在一起(外键存在于DB表中)。我无法弄清楚我缺少什么让孩子保存到数据库。

2 个答案:

答案 0 :(得分:1)

The collection property needs to be virtual

public virtual ICollection<ChildObject> ChildObjects { get; set; }

It's like this with any navigational property, not just collections. Without the virtual keyword, EntityFramework's dynamic proxies are unable to override the property and do the foreign key tracking you want it to do.

答案 1 :(得分:-1)

在ChildObject中创建实例Parent的属性。

public ParentObject Parent { get; set; }

实体框架会检测到有一个外键。您还可以添加ForeignKeyAttribute。