2
votes

I'm having trouble figuring out how to edit an existing entity when posting it to my controller. When I save a new Person, it works just fine, because Id isn't set, so NHibernate views it as a new entity and attaches it to the session. However, when I try to edit an existing entity, the MVC model binder can't set the Id, even though the JSON being posted has it properly set. So even though it's an existing entity, NHibernate again sees it as a new one, and then throws an exception because I'm calling .Update() on an entity that's not in the database or session.

Here's the code I'm using (obviously Person has a lot more properties, I just left them off to keep the code short)

Person class:

public class Person
{
    public virtual int Id {get; private set;}
    //... other properties
}

The JSON being posted to my edit action

{"Id": 10}

And in the controller

public JsonResult EditPerson(Person person)
{
    Session.Update(person);
    return Json(new { success = true});
}
2
How do you map your id ? Is it primary key on your table? - Nic

2 Answers

2
votes

I was always under the impression that you had to load the entity to get it into the session so that you could edit it.

so you would need code like

var entity = Session.Get<Entity>(entity.Id);

//make your changes
Session.Save(entity);
1
votes

Try

public virtual int Id {get; protected set;}

NHibernate uses proxies to load and set the properties of your classes, if your setter is private (rather than public or protected) the proxy (which inherits from your mapped class) cannot access it and assign the value it loaded from the database.