Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
753 views
in Technique[技术] by (71.8m points)

c# - Entity Framework and DbContext - Object Tracking

I am a bit confused on the usage of DbContext in Entity Framework. Here's the scenario I'm confused about.

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

  • Then I call again:

    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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

If you just want to refresh transactions but you don't want to lose your changes you can use MergeOption.PreserveChanges instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...