1中更改实体的状态

1中更改实体的状态

本文介绍了在实体框架4.1中更改实体的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个Customer对象,其中有一个Order对象. Order对象具有OrderDetail对象.

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

这仅保存oCustomer对象,而不保存oCustomer中的Order和OrderDetail.由于context.Entry(oCustomer).State = EntityState.Modified仅更改oCustomer的状态,而不会更改Order和OrderDetail.当前,我必须手动更改ObjectGraph中每个实体的状态,以便保存更改.有什么方法可以改变整个ObjectGraph的状态,而不仅仅是父实体?是否有任何扩展方法或其他方法可以做到这一点?

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?

推荐答案

由于您要切断上下文和实体之间的链接,因此不会.它不能自动地知道所有条目都处于修改状态.

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.

您可以创建自己的扩展方法(或将其添加到派生的对象上下文类中)以遍历所有属性,并检查它们是否在配置中映射,如果是,则将它们设置为Modifyed.

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.

这篇关于在实体框架4.1中更改实体的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 22:06