2012-03-05 66 views
7

我遷移這樣的應用程序:NHibernate的集中退出按類型而不是按實例

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

我wan't做這樣的事情:

session.EvictAllByType(typeof(Vehicle)); 

這可能嗎?如何?, 謝謝

+0

你總是可以做一個'session.Clear()'清理會話。 – 2012-03-05 18:16:27

+0

session.clear()清除所有需要清除車輛類型對象的會話對象,thanx – manuellt 2012-03-06 08:40:25

回答

0

恕我直言,我不認爲evict是你的情況下的解決方案,因爲v不屬於第二屆會議(所以如果你驅逐所有車輛是不夠的)。

我的建議是到V連接到第二屆會議,如:

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

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

Thanx @Martha,我的對象可能已經改變了他的狀態,需要更新/合併,我用我的對象做事情,立即我驅逐我的目標,因爲下一個代碼可能需要其他(非我的)車輛進行交互,thanx再次。 – manuellt 2012-03-06 11:05:05

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

+1我今天實現了這一點,這很方便:)不確定究竟在哪裏查看的生存環境。 – Lukazoid 2012-07-25 13:04:45

相關問題