开发者

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

I have paren开发者_高级运维t 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


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();
}


Server doesn't know if entity exists until it loads it from database. So when you add childs on client and send them to the server you also have to include information about new childs, updated childs and deleted childs. If you do not include such information you have to load complete entity graph from DB first and then compare received graph with loaded graph and process changes manually.

Automatic solution for such case can be Self tracking entities (STEs) but still your example will not work. STEs require you to load objects, send them to client, modify them and send them back. STEs will track all changes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜