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).

 

 

参考

Entity Framework 5 - DbContext Has Changes

Entity Framework 6.1 is context dirty

posted @   霍旭东  阅读(789)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示