Ivan
Ivan

Reputation: 1284

nHibernate saveorupdate/merge detached object

Iam doing on application with web services. As ORM I use nHibernate.

Question:

In application layer I load with repository entity with lets say ID (pk) 32 , transform it to viewModel and send it to presentation layer. Session flushed.

Then, user can change data in that entity and send request to application layer for edit data. And here is my question. With request (towards applicatino layer)and all datas as a view model (not enity object) iam sending also an ID but iam not able to create business object with ID (id is generated by nhibernate, private set). Should i use reflection and inject that id and then use nhibernate saveorupdate or merge methods or manually compare and set new values?

Thanks.

Upvotes: 0

Views: 1181

Answers (1)

Jay Otterbein
Jay Otterbein

Reputation: 968

Instead of trying to create the business object with the id, you should load the object from the session to start with. After you load the business object from nhibernate you modify the values based on the edit model, and then update the object.

You don't have to manually compare the fields to see if they changed, nhibernate will handle that for you and only update the DB with the changed fields.

Your method might look like:

public ActionResult Update(EditModel model)
{
    var entity = _session.Get<Entity>(model.Id);
    entity.Name = model.Name;
    entity.Description = model.Description;
    entity.SomeField = model.SomeField;
    _session.SaveOrUpdate(entity);
}

Upvotes: 2

Related Questions