简体   繁体   中英

A different object with the same identifier value was already associated with the session: XXX, of entity

We have a ASP.NET MVC 3 C# project running NHibernate 3 and Castle.ActiveRecord for MySQL, and we trying to get "one session per request" to work with this tutorial .

And it seems to work for some stuff, but when we do SaveAndFlush() , the command gives us an error:

A different object with the same identifier value 
was already associated with the session: 142

And if we try to do only Save() we got the same message so it has nothing to do with the Flush() function.

I have find some result when I search but nothing I can use to get it to work.

Something I have not tested because I don't know how I do, is,

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")

Any ideas?

Basically the problem might lie in that you are trying to Save() an object that already exists. If the object has an identifier already set ( object.Id = 142 ) then the object does not need to be saved.

If you make changes to it, and need to save those changes you need to use the Update() method (as mentioned by @OskarBerggren) or the SaveOrUpdate() which basically checks and decides whether to save the object or update it. The last one might work best in your case. Change your current,

session.Save(object);

to,

session.SaveOrUpdate(object);

The Session object is from NHibernate's SessionFactory implementation. However, I see you are using ActiveRecordMediator , so you can use,

ActiveRecordMediator.GetSessionFactoryHolder().CreateSession()

to create a Session you can use to save your models.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM