Entity Framework 4.1 DbSet Reload

前端 未结 4 1555
抹茶落季
抹茶落季 2020-12-03 11:49

I\'m using a single instance of DbContext scenario to shadow entire copy of the database locally in a WPF app. I\'ve heard this is bad practice, but my database

4条回答
  •  既然无缘
    2020-12-03 12:17

    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.

提交回复
热议问题