实体框架和的DbContext - 目标跟踪 [英] Entity Framework and DbContext - Object Tracking
问题描述
我在的DbContext的实体框架的使用情况有点混乱。这是我感到困惑的场景。
I am a bit confused on the usage of DbContext in Entity Framework. Here's the scenario I'm confused about.
-
我使用LINQ查询从的DbContext获取数据。是这样的:
I use a linq query from the dbcontext to get data. Something like:
List<Transactions> transactions = DefaultContext.Transactions.ToList();
然后,我在查询数据库返回的直接交易的一个更新的一列。
Then I update a column in one of the transactions returned in that query directly in the database.
于是我再次呼吁:
List<Transactions> transactions = DefaultContext.Transactions.ToList();
在列表中就返回这个时候,它并不能反映更新/通过我的所有事务做出的更改我在运行更新语句时作出,除非我环路和重新加载它们:
When the list returns back this time, it doesn't reflect the updates/changes I made when running the update statement, unless I loop through all my transactions and Reload them:
foreach (DbEntityEntry<Transactions> item in DefaultContext.ChangeTracker.Entries<Transactions>())
{
DefaultContext.Entry<Transactions>(item.Entity).Reload();
}
这是正常的行为呢?假设我在我的初始查询,它们连接对象上下文。然后,当我查询的时候,它不会使一个访问数据库,只是拉出的实体对象的情况下,除非我明确/分离或单独重新加载所有的实体。
Is this normal behavior? I assume that on my initial query, they are attached to the object context. Then when I query the second time, it doesn't make a trip to the database, and just pulls out the entities from the object context, unless I clear/detach or individually reload all of the entities.
推荐答案
这是正常的情况下的DbContext API固定的行为,因为一些很奇怪的原因,既不是 DbSet
或的DBQuery
暴露 MergeOption
属性。如果是ObjectContext的API,你可以设置为 MergeOption
的行为暴露在对象集
和的ObjectQuery
。所以,如果你想刷新从数据库中的值(和丢失所做的更改),你可以这样做:
It is normal and in case of DbContext API fixed behaviour because from some very strange reason neither DbSet
or DbQuery
expose MergeOption
property. In case of ObjectContext API you can set the behaviour by MergeOption
exposed on ObjectSet
and ObjectQuery
. So if you want to refresh values from database (and lose your changes) you can do:
ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
ObjectSet<Transactions> set = objectContext.CreateObjectSet<Transactions>();
set.MergeOption = MergeOption.OverwriteChanges;
List<Transactions> transactions = set.ToList();
如果你只是想刷新交易,但你不想失去你改变,你可以使用 MergeOption。preserveChanges
代替。
If you just want to refresh transactions but you don't want to lose your changes you can use MergeOption.PreserveChanges
instead.
这篇关于实体框架和的DbContext - 目标跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!