开发者

NHibernate - lazy loading: no session or session was closed

开发者 https://www.devze.com 2023-02-26 04:20 出处:网络
I\'m confused by the following NHibernate behaviour: Domain classes and mappings: public class Category

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).

0

精彩评论

暂无评论...
验证码 换一张
取 消