2
votes

I'm quite new to nHibernate, so this'll probably be a pretty stupid question. But anyway, saving an object works fine, updating it doesn't work.

This is what I'm doing:

using (ISession session = _sessionFactory.OpenSession())
{
    session.SaveOrUpdate(schemaChange);
    schemaChange.ScriptName = "New one";
    session.SaveOrUpdate(schemaChange);
}

The first SaveOrUpdate inserts a schemaChange in the database. The second one should update the same object, but nHibernate doesn't do that.

In the output I get:

DEBUG - persistent instance of: DotNetMigrations.Core.Domain.SchemaChange

DEBUG - ignoring persistent instance

DEBUG - object already associated with session: [DotNetMigrations.Core.Domain.SchemaChange#129]

UPDATE

Well, as it was so simple (and a stupid question), I found it myself:

session.SaveOrUpdate(schemaChange);
schemaChange.ScriptName = "New one";
session.Flush();

Makes sence. nHibernate is really superior to any orm tool I've worked with.

What I can't seem to figure out is why there's a SaveOrUpdate method... If you're updating, then isn't the object automatically already associated with the session? (because you got it out of the db in the first way. Unless off course you sent it to for example a Flex RIA and it came back)

So, how do you know if the object is already associated, to either do a SaveOrUpdate() or just a Flush()?

1
You could have auto-answered your question and earned a badge here... ^^Romain
Yeah, that would have made my life worthwile ;-)Lieven Cardoen

1 Answers

2
votes

You can use the Method Session.Contains(object) to figure this out. The difference between Save() and Update() is that Save assigns an Id if necessary, wheather Update() fails if the object has no key or the Key does not exist in database.

SaveOrUpdate fixes some issues regarding working with transient objects, if you don't care what the state of the object is you may call it, but isn't the holy grail at all. If you know what state the object has i would suggest to call the exact method.

Hopefully this helps a little bit to clarify.