如何确定实体框架对象是否已更改? [英] How to find out if an Entity Framework object has changed?

查看:193
本文介绍了如何确定实体框架对象是否已更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个被称为 Uczestnik 的对象,它刚刚保存到数据库

I've an object which is called Uczestnik which just got saved to database

var konsultant = uczestnik.Konsultanci; 
uczestnik.Konsultanci = null; // null attached object and reuse it's ID later on for SAVE purposes
uczestnik.KonsultantNazwa = konsultant.KonsultantNazwa;
uczestnik.Szkolenie = null; // null attached object and reuse it's ID later on for SAVE purposes
uczestnik.SzkolenieID = szkolenie.SzkolenieID;                       
context.SzkolenieUczestnicies.AddObject(uczestnik);
context.SaveChanges();
context.Detach(uczestnik); // detatch to prevent Context problems
uczestnik.Szkolenie = szkolenie;// reassign for use in ObjectListView
uczestnik.Konsultanci = konsultant; // reassign for use in ObjectListView   

保存后,它返回到ObjectListView,用户决定更改一些值并且值被改变(一个值从多个确切地)。如果我检查值的实体状态,它处于Unchanged状态,所以调用.Attach和.SaveChanges()不会做任何事情。我可以使用 ChangeObjectState ,但如果没有改变,那么没有任何意义。

After it's saved it's back into ObjectListView where user decided to change some value and the value was changed (one value from multiple to be exact). If I check value's entity state it's in Unchanged state so calling .Attach and .SaveChanges() won't do anything. I can use ChangeObjectState but if there's nothing changed then there's no sense to do so.

context.SzkolenieUczestnicies.Attach(uczestnik);
//context.ObjectStateManager.ChangeObjectState(uczestnik, EntityState.Modified);
context.SaveChanges();

如何检测更改并防止不必要的流量(我可以想像在对象拥有文件5mb大)所以 resaving 这没有任何意义。除非实体足够聪明才能检测到只有一个字段从15改变而只改变该字段?

How can I detect the change and prevent unnecessary traffic (I can imagine situation where nothing is changed in the object that holds files 5mb big) so resaving it makes no sense. Unless Entity is smart enough to detect that only one field was changed from 15 and change only that field?

推荐答案

如果您 Detach 实体,则不会被上下文跟踪。在这种情况下,您将负责检测对象何时更改,并通过使用 ChangeObjectState 通知上下文关于更改。所以你必须跟踪什么用户已经修改或直接实现的东西到您的实体。例如实现 INotifyPropertyChanged (如果您正在使用基于EntityObject的实体,此接口应该已经实现)。

If you Detach entity it is not tracked by the context. In such case you are responsible for detecting when the object has changed and inform the context about changes by using ChangeObjectState. So you must track what user has modified or implement something directly to your entities. For example implement INotifyPropertyChanged (if you are using EntityObject based entities this interface should be already implemented).

这篇关于如何确定实体框架对象是否已更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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