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

转载于:https://www.cnblogs.com/HQFZ/p/4159100.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值