0

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?

rae1
  • 6,066
  • 4
  • 27
  • 48
RickardP
  • 2,558
  • 7
  • 34
  • 42
  • 1
    Are you aware of the difference between Save(), Update(), and that Save() should only be used for _new_ persistent entities? – Oskar Berggren Jan 18 '13 at 12:34
  • The text in SaveAndFlush on the object/model says that its updates if its alrady exists... we have used this for many years in our application but now when we change to "one-session-per-request" its starts to be a problem... – RickardP Jan 18 '13 at 16:31

1 Answers1

1

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.

rae1
  • 6,066
  • 4
  • 27
  • 48