gpt4 book ai didi

c# - NHibernate - 延迟加载 : no session or session was closed

转载 作者:太空宇宙 更新时间:2023-11-03 20:34:26 24 4
gpt4 key购买 nike

我对以下 NHibernate 行为感到困惑:
域类和映射:

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

引起问题的代码:

    Category category;

using (var session = sessionFactory.OpenSession())
{
category = session.Get<Category>(1);
}

using (var session = sessionFactory.OpenSession())
{
var products = category.Products; // exception
}

为什么我尝试获取产品时没有出现 session 异常?我在这里开会!如何避免这个异常(我在这里更喜欢2个 session ,我想保持懒惰加载)?
提前致谢!

最佳答案

您能否将对象重新附加到您的新 session :

ISession.Update(myDetachedInstance);  

或者,如果对象没有被改变:

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

有关详细信息,请参阅:http://intellect.dk/post/Detached-objects-in-nHibernate-and-Lazy-loading.aspx

关于c# - NHibernate - 延迟加载 : no session or session was closed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5702968/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com