Add child object to parent
I'm trying to implement a simple one-to-many relationship with Entity Framework and Code First. I set my parent class in a simple way :
public class Parent
{
[Key]
public long ParentId { get; set; }
public ICollection<Child> Child { get; set; }
public Parent()
{
Child = new HashSet<Child>();
}
}
This is a simplified version of course. My child class is as simple as the parent one :
public class Child
{
[Key]
public long ChildId { get; set; }
public int ParentId { get; set; }
public virtual Parent parent { get; set; }
}
My controllers are the ones generated by EF. Problem is that when I create a Child with a Parent Id in my post method, the ID is set in the database but when I'm getting the parent, the children list is empty.
I've tried adding the child in the parent in the controller like so :
db.parent.find(child.parentId).Child.Add(child);
which apparently had no effect.
The parent in the child object is null and the child list in the parent is empty.
How can I get the child in the parent's collection ?
Thank you !
As far as I know, disabling proxy creation will also affect lazy loading. Lazy loading can only work within the proxy class. If not, then EF does not have any way to control when you're accessing the properties.
The only way you can get the childs is to use eager loading (using the Include())
链接地址: http://www.djcxy.com/p/37660.html上一篇: 在linq实体框架中计数孩子匹配
下一篇: 将子对象添加到父项