Changing Entity's State in Entity Framework 4.1

核能气质少年 提交于 2019-12-13 16:04:25

问题


Let say we have a Customer object which has an Order object. The Order object has OrderDetail object.

Customer oCustomer 
using(var context = new MyContext)
{
oCustomer = context.Include("Order.OrderDetail").Find(1);
}
oCustomer.Name ="blah blah";
oCustomer.Order.Description = "blah blah";
oCustomer.Order.OrderDetail.Quantity = 10;

Now when I change the state of Customer as following:

using(var context = new MyContext)
{
    context.Entry(oCustomer).State = EntityState.Modified.
    context.SaveChanges();
}

This saves only oCustomer object and not the Order and OrderDetail that are in oCustomer. Since context.Entry(oCustomer).State = EntityState.Modified changes state of oCustomer only and not the Order and OrderDetail. Currently, I have to change the state of each entity in the ObjectGraph manually so that the changes are saved. Is there any way to change the state of whole ObjectGraph instead of just the parent entity? Is there any extension method or any other way out to do that?


回答1:


Since you are cutting the link between the context and the entity, no. It can not automagically know all the entries are in the modified state.

You could create your own extension method (or add it to your derived object context class) to walk over all the properties and check if they are mapped in the configuration and if so, set them to modified.

I assume you're working in a disconnected environment, the easiest way is to redo all the changes you've don in the other process. Load the entity from the db again, and populate the properties and call save changes.



来源:https://stackoverflow.com/questions/7008389/changing-entitys-state-in-entity-framework-4-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!