NHibernate Evict By Type instead of by instance
Asked Answered
V

2

7

I'm migrating an application like this:

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 wan't to do something like this:

    session.EvictAllByType(typeof(Vehicle));

is it possible? how?, thanks

Vamp answered 5/3, 2012 at 16:4 Comment(2)
You can always do a session.Clear() to clean up the session.Bostic
session.clear() clears all sessioned objects i need to clear only Vehicle type objects, thanxVamp
S
8

This question may be old, but I ended up here while searching for how to do it. So this is how I ended up doing 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;
    }
Shotgun answered 23/7, 2012 at 21:14 Comment(1)
+1 I implemented this today and this came in handy :) Wasn't sure where exactly to look in the peristence context.Tiatiana
A
0

IMHO I don't think evict is the solution in your case since the v doesn't belong to the 2nd session (so if you evict all vehicles is not enough).

My suggestion is to attach v to the second session like:

...
using (ISession session = MyNHibernateSession())
{
     session.Lock(v, LockMode.None);

     // somwwhere into these4 lines Vehicle comes Finded
...
Assizes answered 5/3, 2012 at 18:5 Comment(1)
Thanx @Martha, my object maybe has changed his state and needs to be updated/merged, i do things with my object, inmediately i evict my object, because the next code maybe needs other (non mine) vehicles to interrrogate, thanx again.Vamp

© 2022 - 2024 — McMap. All rights reserved.