当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - NHibernate - lazy loading: no session or session was closed

问题描述:

I'm confused by the following NHibernate behaviour:

Domain classes and mappings:

public class Category

{

public virtual int ID { get; set; }

public virtual string Name { get; set; }

private IList<Product> _products;

public virtual IList<Product> Products

{

get { return new List<Product>(_products).AsReadOnly(); }

}

public Category()

{

_products = new List<Product>();

}

}

public class Product

{

public virtual int ID { get; set; }

public virtual string Name { get; set; }

public virtual Category Category { get;set; }

}

public class ProductMap : ClassMap<Product>

{

public ProductMap()

{

Schema("dbo");

Table("tProducts");

Id(x => x.ID);

Map(x => x.Name);

References(x => x.Category).Column("CategoryID");

}

}

public class CategoryMap : ClassMap<Category>

{

public CategoryMap()

{

Schema("dbo");

Table("tCategories");

Id(x => x.ID);

Map(x => x.Name);

HasMany(x => x.Products)

.KeyColumn("CategoryID")

.Access.CamelCaseField(Prefix.Underscore)

.Inverse()

.Cascade.All();

}

}

Code causing trouble:

 Category category;

using (var session = sessionFactory.OpenSession())

{

category = session.Get<Category>(1);

}

using (var session = sessionFactory.OpenSession())

{

var products = category.Products; // exception

}

Why do I get no session exception when I'm trying to get products? I've got a session here! How to avoid this exception (I prefer 2 sessions here, and I want to keep loading lazy)?

Thanks in advance!

网友答案:

Can you re-attach the object to your new session either:

ISession.Update(myDetachedInstance);  

or, if the object has not been changed:

ISession.Lock(myDetachedInstance, NHibernate.LockMode.None);  

For more info, see: http://intellect.dk/post/Detached-objects-in-nHibernate-and-Lazy-loading.aspx

网友答案:

I got this same error and it was due to the WPF UI holding on to references to objects from the old nhibernate session after I clicked the "refresh" button which called refresh on the data context which disassociated all cached objects in the session.

I needed to make sure "NotifyChange" was being fired to make the UI update (and that the UI was listening to it).

分享给朋友:
您可能感兴趣的文章:
随机阅读: