Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - Add reference to child object without retrieving entire list of objects?

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

like image 391
David Avatar asked Dec 08 '10 15:12

David


People also ask

How to include a child class in EF Core?

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 :

How do I tell EF that there is a parent-child relation?

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.

What happens when you reference a new entity from another entity?

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.

Is it possible to add a range in Entity Framework 6?

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:


1 Answers

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();
}
like image 63
Craig Stuntz Avatar answered Oct 19 '22 17:10

Craig Stuntz