2

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()?

2
  • You could have auto-answered your question and earned a badge here... ^^ Commented Dec 17, 2009 at 21:06
  • Yeah, that would have made my life worthwile ;-) Commented Dec 18, 2009 at 8:05

1 Answer 1

2

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.

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

Comments

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.