开发者

Saving child entity via WCF using EntityFramework 4.1

Say I have a Person and an Address object where a Person has a list of Address objects. The info is exposed via WCF services, and I'm trying to use EntityFramework 4.1.

If I want to update an Address object on a Person, I want to have a WCF method called UpdateAddress(Address addr).

The DBContext only seems to have a list of Person of which there is a list of Address in the Person object. Is that the only way to update an Ad开发者_C百科dress as it seems that implies it needs to load all of the Person to find an Address to update before saving making it inefficient.

Is there a way to just update without loading the parent entity?


If Person is part of the model and Person has a collection of Address then also Address (as a related entity) is part of the model (unless you excluded the Address collection explicitely from the model). That means you can simply add the Address set to the DbContext as a helper property:

public class MyContext : DbContext
{
    public DbSet<Person> People { get; set; }
    public DbSet<Address> Addresses { get; set; }
}

For UpdateAdress you can then use:

public void UpdateAddress(Address addr)
{
    using (var context = new MyContext())
    {
        var addressInDb = context.Addresses.Find(addr.Id);
        context.Entry(addressInDb).CurrentValues.SetValues(addr);
        context.SaveChanges();
    }
}

Even if you don't want or can't add an Addresses DbSet to the context you can use the Set<T>() method of the context (as long as T is a model entity - and Address should be one):

public void UpdateAddress(Address addr)
{
    using (var context = new MyContext())
    {
        var addressInDb = context.Set<Address>().Find(addr.Id);
        context.Entry(addressInDb).CurrentValues.SetValues(addr);
        context.SaveChanges();
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜