EF6 如何判断DataContext有修改,以及如何放弃修改
如何判断DataContext有修改:
EF6的
using (var db = new Model1()) { if (db.ChangeTracker.HasChanges()) { Console.WriteLine("Something has changed"); } }
EF5中:
public bool HasUnsavedChanges() { return this.ChangeTracker.Entries().Any(e => e.State == EntityState.Added || e.State == EntityState.Modified || e.State == EntityState.Deleted); }
EF4中为:
public Boolean HasUnsavedChanges() { return (this.ObjectContext().ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted).Any()); }
DataContext如何放弃修改的建议:
this is not supposed way to use context. Context is unit of work - do changes you really want to do and then save them. If you find that you don't want to save changes dispose the context and create a new one. The best practice is using context for one single logical operation. Sharing context or using static context is a bad practice and because of that there is no build in method to "reset" context - you must do it yourselves by exploring ObjectStateManager and reverting all changes (it can be quite complex task).
参考
作者:旭东
出处:http://www.cnblogs.com/HQFZ
关于作者:专注于微软平台项目架构、管理和企业解决方案。现主要从事WinForm、ASP.NET、WPF、WCF、等方面的项目开发、架构、管理。如有问题或建议,请不吝指教!
本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。如有问题,可以联系我,非常感谢。
如果您该文觉得不错或者对你有帮助,请点下推荐,让更多的朋友看到,谢谢!