在实体框架中更新断开的对象 [英] update disconnected object in entity framework

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

问题描述

我有一些数据来自其他层,它代表一个EF对象。
当它是新的,我这样做:

  context.AddToCustomer(mynewobject); 
context.SaveChanges();

但现在我的数据形成了一个现有的对象,所以我想让上下文知道我想更新数据而不是插入它。



我看过'ApplyPropertyChanges',但是我不知道如何使用它。
我也看到人们这样做:

  Customer existingOne =(from n in context.Customers 
其中n.id = mynewobject.id选择n).First()
existingOne.name = mynewobject.name
existingOne.address = mynewobject.address
context.SaveChanges();

但这似乎有点奇怪,因为我必须手动设置所有道具,并先阅读整个对象

解决方案

虽然我质疑优化更新是否值得,但您仍然可以做所要求的事情。 在EF 4中更容易,而且 。另请参阅这篇文章

  public static void AttachAsModified< T>(此ObjectSet< T> objectSet,T entity)其中T:class 
{
objectSet.Attach实体);
objectSet.Context.ObjectStateManager.ChangeObjectState(entity,EntityState.Modified);
}


I have some data coming from other tiers and it represents an EF object. When it's new, I do this:

context.AddToCustomer(mynewobject);
context.SaveChanges();

but now my data forms an existing object, so I want the context to know I want to update the data and not inserting it.

I've seen 'ApplyPropertyChanges' but I can't figure out how to use it. I've also seen people doing this:

Customer existingOne = (from n in context.Customers 
                        where n.id = mynewobject.id select n).First()
existingOne.name = mynewobject.name
existingOne.address= mynewobject.address
context.SaveChanges();

but that seems a little odd because I have to manually set all the props AND read the entire object first.

解决方案

While I question whether it's even worthwhile to "optimize" an update, you can nevertheless do what you ask. It's easier in EF 4, but also possible in EF 1. See also this article.

public static void AttachAsModified<T>(this ObjectSet<T> objectSet, T entity) where T : class
{
    objectSet.Attach(entity);
    objectSet.Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆