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?