[英]NHibernate Evict throws an Object reference not set to an instance of an object error
[英]NHibernate Evict By Type instead of by instance
我正在遷移這樣的應用程序:
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));
可能嗎? 怎么樣?謝謝
這個問題可能已經過時了,但我在搜索如何操作時最終到了這里。 所以這就是我最終做到的方式:
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;
}
恕我直言我不認為evict是你的情況下的解決方案,因為v不屬於第二屆(所以如果你驅逐所有車輛是不夠的)。
我的建議是將v附加到第二個會話,如:
...
using (ISession session = MyNHibernateSession())
{
session.Lock(v, LockMode.None);
// somwwhere into these4 lines Vehicle comes Finded
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.