Detaching all entities of T to get fresh data

Posted by Goran on Stack Overflow See other posts from Stack Overflow or by Goran
Published on 2014-08-25T12:34:22Z Indexed on 2014/08/25 16:20 UTC
Read the original article Hit count: 249

Lets take an example where there are two type of entites loaded: Product and Category, Product.CategoryId -> Category.Id. We have available CRUD operations on products (not Categories).

If on another screen Categories are updated (or from another user in the network), we would like to be able to reload the Categories, while preserving the context we currently use, since we could be in the middle of editing data, and we do not want changes to be lost (and we cannot depend on saving, since we have incomplete data).

Since there is no easy way to tell EF to get fresh data (added, removed and modified), we thought of twp possible ways:

1) Getting products attached to context, and categories detached from context. This would mean that we loose the ability to access Product.Category.Name, which we do sometimes require, so we would need to manually resolve it (example when printing data).

2) detaching / attaching all Categories from current context.

Context.ChangeTracker.Entries().Where(x => x.Entity.GetType() == typeof(T)).ForEach(x => x.State = EntityState.Detached);

And then reload the categories, which will get fresh data. Do you find any problem with this second approach? We understand that this will require all constraints to be put on foreign keys, and not navigation properties, since when detaching all Categories, Product.Category navigation properties would be reset to null also. Also, there could be a potential performance problem, which we did not test, since there could be couple of thousand products loaded, and all would need to resolve navigation property when reloading.

Which of the two do you prefer, and is there a better way (EF6 + .NET 4.0)?

© Stack Overflow or respective owner

Related posts about wpf

Related posts about entity-framework