Optimistic update

Here is the classic pattern of entities detachment / attachment:


We get the entity.
We send the entity to the client which clone it.
To update entity, the client send to the server the initial entity and the modified one.
Then, the server instanciates a new context, attaches the initial entity, call the ApplyPropertyChanges method with modified entity and then saves the context.


However, if you don’t want to keep the possible updates of the DB row between the send to the client and the save of the server, you don’t need the initial entity.
Before ApplyPropertyChanges, the initial entity must be on the context. Here, you can get the entity with latest DB row with TryGetObjectByKey method. Then, you just need to use ApplyPropertyChanges and SaveChanges methods to update the DB.


This sample is not a client/server code but it allows to check my solution.


NorthwindModel.Categories c;

NorthwindModel.Categories c2;

using (var context = new NorthwindModel.NorthwindEntities())

{

    context.Categories.MergeOption = System.Data.Objects.MergeOption.NoTracking;

    c = context.Categories.First();

}

using (var context = new NorthwindModel.NorthwindEntities())

{

    c2 = context.Categories.First();

    context.DeleteObject(c2);

    context.SaveChanges();

}

using (var context = new NorthwindModel.NorthwindEntities())

{

    object o;

    context.TryGetObjectByKey(c.EntityKey, out o);

    context.ApplyPropertyChanges(“Categories”, c);

    context.SaveChanges();

}


With attachment, ApplyPropertyChanges, the SaveChanges method do nothing if the DB row was deleted.
Previous code throws an exception on ApplyPropertyChanges method if DB row was deleted. But with this following code we have no exception and the DB row is created again.


NorthwindModel.Categories c;

NorthwindModel.Categories c2;

using (var context = new NorthwindModel.NorthwindEntities())

{

    context.Categories.MergeOption = System.Data.Objects.MergeOption.NoTracking;

    c = context.Categories.First();

}

using (var context = new NorthwindModel.NorthwindEntities())

{

    c2 = context.Categories.First();

    context.DeleteObject(c2);

    context.SaveChanges();

}

using (var context = new NorthwindModel.NorthwindEntities())

{

    object o;

    context.TryGetObjectByKey(c.EntityKey, out o);

    if (o == null)

        context.AddToCategories(c);

    else

        context.ApplyPropertyChanges(“Categories”, c);

    context.SaveChanges();

}

This entry was posted in 7671, 7674. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>