tags:

views:

123

answers:

3

Can we update Id fields in NHibernate like the following?

MyClass myObj = MyClass.Retrieve(1);

myObj.Id = 999;
myObj.Name = "name name";
myObj.Value = 1000;

MyClass.Update(myObj);
A: 

Something like this will work:

ISession.Delete(yourClass);
yourClass.Id = somethingelse;
ISession.Save(yourClass);

Why do you want to change an Identifier? It sounds like a very bad thing to do.

Paco
first of all, I agree - changing an identifier is a bad idea to begin with. But your "solution" here doesn't work either, if that entity has been referenced by other entities - if you have referential integrity in place, you usually cannot just simply delete a row from a table and re-create it.....
marc_s
That's true, than you have to create a deep copy of the whole aggregate root
Paco
+2  A: 

You should never change the identifier (primary key) on an existing object. With NHibernate, you should only assign the identifier on new objects if you've mapped the generator as "assigned". If you're intent is to clone an existing object, then retrieve the object and create the clone as a new instance so that a new identifier is assigned.

Jamie Ide
thats not helpful
usr
Why not? Changing a primary key is a terrible idea. My guess is that the original question was in regards to a cloning process.
Jamie Ide
A: 

You can close the session, execute raw sql to change the primary key, and then open a new session. that is the only thing that works as nhibername relies on primary key identity. you will never ever be able to make nhibernate do it.

usr