0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Diego, you're a lifesaver as always :). And thanks for the tip, that saves me quite a bit of code!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.