views:

24

answers:

1

Let's say I have an entity like so:

public class Product
{
    public virtual int Id { get; set; }
    public virtual int Name { get; set; }
}

A client wants to update the name of a particular product, so he sends this JSON back to an ASP.NET server:

{
    "Id": 1,
    "Name": "Updated Product Name"
}

I then run this code to try and save it:

var jsonString = GetJsonStringFromRequestBody();
var product = JsonNet.Deserialize<Product>(jsonString);

using (var session = SessionFactory.OpenSession())
{
    session.Update(product);
}

Unfortunately, I get the following exception:

NHibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

Now, I could use the following code instead:

var jsonString = GetJsonStringFromRequestBody();
var productToUpdate = JsonNet.Deserialize<Product>(jsonString);

using (var session = SessionFactory.OpenSession())
{
    var productFromDB = session.Linq<Product>().Single(x => x.Id == productToUpdate.Id);
    productFromDB.Name = productToUpdate.Name;
}

But unfortunately, that requires manually copying over every property from the deserialized entity to the persistent one. Is there an easier or better way of doing this?

A: 

Retrieving from the DB and updating is the safest way. You can use reflection if you want to write less code.

By the way, using Linq to select by id is a waste: use session.Get<Product>(id) instead.

Diego Mijelshon
Diego, you're a lifesaver as always :). And thanks for the tip, that saves me quite a bit of code!
Daniel T.
You're welcome :-D
Diego Mijelshon