Note that there are some explanatory texts on larger screens.

plurals
  1. POHandle concurrency in Entity Framework
    primarykey
    data
    text
    <p>I am looking for the best way to handle concurrency while using Entity Framework. The simplest and most recommended (also on stack) solution is described here: <a href="http://msdn.microsoft.com/en-us/library/bb399228.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb399228.aspx</a> And it looks like:</p> <pre><code>try { // Try to save changes, which may cause a conflict. int num = context.SaveChanges(); Console.WriteLine("No conflicts. " + num.ToString() + " updates saved."); } catch (OptimisticConcurrencyException) { // Resolve the concurrency conflict by refreshing the // object context before re-saving changes. context.Refresh(RefreshMode.ClientWins, orders); // Save changes. context.SaveChanges(); Console.WriteLine("OptimisticConcurrencyException " + "handled and changes saved"); } </code></pre> <p>But is it enough? What if something changes between Refresh() and the second SaveChanges()? There will be uncaught OptimisticConcurrencyException?</p> <p>EDIT 2:</p> <p>I think this would be the final solution:</p> <pre><code> int savesCounter = 100; Boolean saveSuccess = false; while (!saveSuccess &amp;&amp; savesCounter &gt; 0) { savesCounter--; try { // Try to save changes, which may cause a conflict. int num = context.SaveChanges(); saveSuccess = true; Console.WriteLine("Save success. " + num.ToString() + " updates saved."); } catch (OptimisticConcurrencyException) { // Resolve the concurrency conflict by refreshing the // object context before re-saving changes. Console.WriteLine("OptimisticConcurrencyException, refreshing context."); context.Refresh(RefreshMode.ClientWins, orders); } } </code></pre> <p>I am not sure if Iunderstand how the Refresh() works. Does it refresh whole context? If yes, why does it take additional arguments (entities objects)? Or does it refreshes only objects specified? For example in this situation what should be passed as Refresh() second argument:</p> <pre><code>Order dbOrder = dbContext.Orders.Where(x =&gt; x.ID == orderID); dbOrder.Name = "new name"; //here whole the code written above to save changes </code></pre> <p>should it be dbOrder?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload