Adam Hey
Adam Hey

Reputation: 1691

Must Nhibernate Session.Evict() act on a proxy object? (Or is there an alternative way to clone a persisted object graph?)

I am trying to create a clone of a persisted object graph and it seems like Session.Evict(PersistedObject) is the way to do this. By removing the instance from the Session cache, I can then set persist it as a new "cloned" record.

I have tried three approaches and each has been unsuccessful.

  1. Use eager loading to get my object graph from the db and attempt to Evict it. This results in a KeyNotFoundException
  2. Use Session.Load(objectId) and attempt to evict it. Evict works, but I only have a proxy to work with and not the hydrated object I need
  3. Use Session.Get(objectId) and attempt to Evict it. This results in a KeyNotFoundException

I've struggled to find any real documentation or examples on this subject. I've found some that come close, but nothing that really explains where I'm going wrong

With regards to the last link, I have checked my Equals and GetHashCode methods, but they do not get hit when calling Evict. Also, Session.Contains(objectToBeEvicted) returns true just prior to the Evict()

As for the second question in the title - is there a better way to approach this problem? This can't be such a rare scenario

Thanks in advance

Upvotes: 0

Views: 321

Answers (2)

Oskar Berggren
Oskar Berggren

Reputation: 5647

To answer the initial question:

No, Evict() is not limited to acting on proxies, it can remove any object from the session. If you are getting some sort of exception, most likely you are doing something wrong, but the question does not contain enough information to figure out what.

Upvotes: 1

shfire
shfire

Reputation: 847

Try to make a deep clone (.Net Deep cloning - what is the best way to do that?) of your object and then add it to the session.

Upvotes: 0

Related Questions