NHibernate Evict By Type instead of instance

I port the application as follows:

Vehicle v = null; using (ISession session = MyNHibernateSession()) { v = Vehicle.FindById(1); } using (ISession session = MyNHibernateSession()) { // somwwhere into these4 lines Vehicle comes Finded DoSomething(); DoSomething2(); DoSomething3(); DoSomething4(); DoSomething5(); DoSomething6(); // if i do this i get an error "another object with the same id etc etc etc session.Update(v); } 

I will not do something like this:

  session.EvictAllByType(typeof(Vehicle)); 

Is it possible? how ?, thanks

+7
source share
2 answers

This question may be old, but I ended up here when I was looking for how to do this. So here is how I did it:

  public static void EvictAll<T>(this ISession session, Predicate<T> predicate = null) { if (predicate == null) predicate = x => true; foreach (var entity in session.CachedEntities<T>().Where(predicate.Invoke).ToArray()) session.Evict(entity); } public static IEnumerable<T> CachedEntities<T>(this ISession session) { var sessionImplementation = session.GetSessionImplementation(); var entities = sessionImplementation.PersistenceContext.EntityEntries.Keys.OfType<T>(); return entities; } 
+7
source

IMHO I do not think that eviction is the solution in your case, since v does not belong to the 2nd session (so if you evict all vehicles, it’s not enough).

My suggestion is to attach v to the second session, for example:

 ... using (ISession session = MyNHibernateSession()) { session.Lock(v, LockMode.None); // somwwhere into these4 lines Vehicle comes Finded ... 
0
source

All Articles