Search code examples
entity-framework-4concurrencyrefresh

which is the difference betwwen this two ways to refresh the dbContext?


I am using EF 4.4 and I would like to update many entities, but some other user can modified many of the entities that the first user is modified. So I get a concurrency exception. Other case is that the first user tries to add many new registers and other user added some of them meanwhile. So I have an exception that exists some of the registers (unique constraint).

I would like to ensure that the first user finish his operation add only the registers that does no exists yet (add all his entities except the entities that are added by the second user).

To do that, I need to update the entities in my dbContext so I see that there at least two options.

First, in the catch when I capture the update exception, I can do:

ex.Entries.Single().Reload();

The second option is:

myContext.Entry<MyTable>(instance).Reload();

I guess that the second option only refreshes the entity that I use as parameter, but if the problem is that I need to refresh many entities, how can I do that?

What really does the first option, Single().Reload?


Solution

  • When you do

    ex.Entries.Single().Reload();
    

    you are sure that the offending entity is refreshed. What is does is taking the one and only (Single) entity from the DbUpdateConcurrencyException.Entries that could not be saved to the database (in case of a concurrency exception this is always exactly one).

    When you do

    myContext.Entry(instance).Reload();
    

    You are not sure that you refresh the right entity unless you know that only one entity had changes before SaveChanges was called. If you save an entity with child entities any one of them can cause a concurrency problem.