NHibernate - updating Identity fields

十年热恋 提交于 2019-12-24 08:32:05

问题


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);

回答1:


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.




回答2:


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.




回答3:


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.




回答4:


I had to add a Evict after delete then work.

Something like this will work:

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

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

This is what I did:

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


来源:https://stackoverflow.com/questions/1024477/nhibernate-updating-identity-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!