【问题标题】:NHibernate Evict By Type instead of by instanceNHibernate 按类型驱逐而不是按实例驱逐
【发布时间】:2012-03-05 16:04:19
【问题描述】:

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

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);
}

我不想做这样的事情:

    session.EvictAllByType(typeof(Vehicle));

有可能吗?如何?, 谢谢

【问题讨论】:

  • 您可以随时使用session.Clear() 来清理会话。
  • session.clear() 清除所有会话对象我只需要清除车辆类型对象,thanx

标签: c# nhibernate session isession


【解决方案1】:

这个问题可能很老,但我在寻找如何做的时候来到了这里。所以这就是我最终这样做的方式:

    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;
    }

【讨论】:

  • +1 我今天实现了这个,它派上用场了 :) 不确定在持久性上下文中究竟应该在哪里查看。
【解决方案2】:

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

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

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

     // somwwhere into these4 lines Vehicle comes Finded
...

【讨论】:

  • Thanx @Martha,我的对象可能已经改变了他的状态,需要更新/合并,我用我的对象做事,我立即驱逐我的对象,因为下一个代码可能需要其他代码(非我的) 车辆进行审讯,再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-17
  • 2012-06-07
  • 2019-03-04
  • 1970-01-01
  • 2012-07-16
  • 1970-01-01
相关资源
最近更新 更多