NHibernate Evict按类型而不是实例

man*_*llt 7 c# nhibernate session isession

我正在迁移这样的应用程序:

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);
}
Run Code Online (Sandbox Code Playgroud)

我不想做这样的事情:

    session.EvictAllByType(typeof(Vehicle));
Run Code Online (Sandbox Code Playgroud)

可能吗?怎么样?谢谢

小智 7

这个问题可能已经过时了,但我在搜索如何操作时最终到了这里.所以这就是我最终做到的方式:

    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;
    }
Run Code Online (Sandbox Code Playgroud)


Mar*_*tha 0

恕我直言,我不认为驱逐是你的情况的解决方案,因为 v 不属于第二次会议(所以如果你驱逐所有车辆是不够的)。

我的建议是将 v 附加到第二个会话,例如:

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

     // somwwhere into these4 lines Vehicle comes Finded
...
Run Code Online (Sandbox Code Playgroud)