Entity Framework 4.1 DbSet Reload

走远了吗. 提交于 2019-11-27 14:25:46
Ladislav Mrnka

This is not the way you are supposed to use DbContext, and because of that it is almost impossible to reload the data. Keeping a single context around for a long time is incorrect usage. The link will also answer why your tracked entities are not updated.

You can selectively reload a single entity by calling Reload on DbEntityEntry:

context.Entry(entity).Reload();

You can also revert back to ObjectContext and use ObjectQuery with MergeOption.OverrideChanges, or use Refresh for a collection of entities with RefreshMode.StoreWins.

All these approaches suffers some problems:

  • If the record is deleted in the database, it will not be removed from the context.
  • Changes in relations are not always refreshed.

The only correct way to get fresh data is Dispose the context, create a new one and load everything from scratch - and you are doing this anyway.

With Entity Framework 4.1, the recommendation for WPF data binding has changed to use .Local and a persistent DbContext.

http://blogs.msdn.com/b/efdesign/archive/2010/09/08/data-binding-with-dbcontext.aspx

It's, of course, possible to dispose of it whenever you need to, but it can negatively impact the UI if you do.

Here's another method, but I'm not sure that it takes EF4.1's features into account:

http://msdn.microsoft.com/en-us/library/cc716735.aspx

DbContexts are supposed to live short time, Consider after saving changes disposing it and reloading all from the start. Have 2 sets of objects.. one from db and another for binding.

user3218010

Please use using() for CRUD.It will automatically reload the updated data.

using (myDbContext context = new myDbContext())
{

}

Best Regards, Thet Tin Oo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!