I have parent object which has childs property which is itself an collection object. ie. Parent.Childs I am exposing these EF object through WCF. Said another way parent can have multiple children as in the case of Invoice(parent) and LineItems (childs).
Client side how do i reference a Child object and add it to the Childs collection without going through the service and getting the entire list of children and setting manually Parent.Childs.Add(child) for each child object that matches.
I would like to do something like Parent.Childs = new Childs(){ new Child{childId=1}, new Child{childId=2}}; and then when i send Parent to server the server knows that a children with id=1 and id=2 already exists and hooks it up. I am sure there is away.
I was reading about EntityKey property but my objects client side do not have this property at all.
thanks
With EF Core in .NET Core you can use the keyword ThenInclude : return DatabaseContext.Applications .Include (a => a.Children).ThenInclude (c => c.ChildRelationshipType); Include childs from childrens collection :
The key here is that I'm using conventions to tell EF that there is a parent-child relations. Notice how the id names used between the two entities match up. The child has a ParentId that matches ParentId in its parent. Also noticed the foreign key constraint in the child.
If you reference a new entity from the navigation property of an entity that is already tracked by the context, the entity will be discovered and inserted into the database. In the following example, the post entity is inserted because it is added to the Posts property of the blog entity which was fetched from the database.
I am working with Entity Framework 6. ` Also, you can use the AddRange method, but first you have to filter your collection as @ChrisPratt suggests in his answer:
using(var context = new MyEntities())
{
var child1 = new Child{ childId = 1 };
context.Children.Attach(child1);
var parent = new Parent();
parent.Children.Add(child1);
context.SaveChanges();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With