Tuesday, 10 September 2013

How to add a child to the parent's list in Entity Framework

How to add a child to the parent's list in Entity Framework

I have Entity Framework Entity, called Detail and it has a property Files
which is linked to another Entity File. 1 Detail can have multiple Files.
In the DB they are linked via Login field. So when I update Detail entity,
I also need to insert the new records into the File entity.
I tried several ways, none of them worked out: Detail connectedObj =
context.Details.Include("USState").SingleOrDefault(p => p.Login ==
model.Login); if (connectedObj.Files != model.ImgFiles) { foreach (var
itemmodel in model.Files)
1 way: context.Detail.Attach(connectedObj);
context.Files.AddObject(itemmodel);
connectedObj.ImgFiles.Add(itemmodel);
2 way: connectedObj.Files.Add(itemmodel);
3 way: context.Files.Attach(itemmodel);
context.ObjectStateManager.ChangeObjectState(itemmodel,
EntityState.Added);
4 way: itemmodel.Detail = connectedObj;
context.Files.AddObject(itemmodel);
context.ObjectStateManager.ChangeObjectState(connectedObj,
EntityState.Unchanged);
}}
Please advise, how can I properly insert the child to the list of the parent?

No comments:

Post a Comment