码迷,mamicode.com
首页 > 其他好文 > 详细

EF6 如何判断DataContext有修改,以及如何放弃修改

时间:2014-12-12 11:23:58      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   for   

 

如何判断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).

 

 

参考

Entity Framework 5 - DbContext Has Changes

Entity Framework 6.1 is context dirty

EF6 如何判断DataContext有修改,以及如何放弃修改

标签:style   blog   http   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/HQFZ/p/4159100.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!