预加载、延迟加载
其他相关类和配置文件参考入门(五)
EagerLoading.cs预加载类:
public class EagerLoading
{
ISessionFactory sessionFactory = new Configuration().Configure().BuildSessionFactory();
protected object CustomerId=1;
public void EagerLoadingCollection()
{
using (var session = sessionFactory.OpenSession())
{
Customer customer = session.Get<Customer>(CustomerId);
if (customer.Orders.Count>0)
{
customer.Orders.ForEach(o=> Console.WriteLine(o.Id));
}
}
}
public void EagerLoadingCollectionAfterSession()
{
Customer customer;
using (var session = sessionFactory.OpenSession())
{
customer = session.Get<Customer>(CustomerId);
}
if (customer.Orders.Count > 0)
{
customer.Orders.ForEach(o => Console.WriteLine(o.Id));
}
}
}
LazyLoading.cs延迟加载类:
public class LazyLoading
{
ISessionFactory sessionFactory = new Configuration().Configure().BuildSessionFactory();
protected object CustomerId = 1;
public void LazyLoadingCollection()
{
using (var session = sessionFactory.OpenSession())
{
Customer customer = session.Get<Customer>(CustomerId);
if (customer.Orders.Count > 0)
{
customer.Orders.ForEach(o => Console.WriteLine(o.Id));
}
}
}
//延迟加载,可能会引起session已经关闭的异常,例如:
//当实现延迟加载,当需要Orders时,会通过session去查询,session。但此时,由于session已经关闭,
//所以会抛出异常:no session or session was closed
public void LazyLoadingCollectionAfterInitialization()
{
Customer customer;
using (var session = sessionFactory.OpenSession())
{
customer = session.Get<Customer>(CustomerId);
//强制立即加载
NHibernateUtil.Initialize(customer.Orders);
}
if (customer.Orders.Count > 0)
{
customer.Orders.ForEach(o => Console.WriteLine(o.Id));
}
}
public void LazyLoadingCollectionAfterSession()
{
Customer customer;
using (var session = sessionFactory.OpenSession())
{
customer = session.Get<Customer>(CustomerId);
}
NHibernateUtil.IsInitialized(customer.Orders);
if (customer.Orders.Count > 0)
{
customer.Orders.ForEach(o => Console.WriteLine(o.Id));
}
}
}
程序主入口
class Program
{
static void Main(string[] args)
{
//---------------------------------------------------
//EagerLoading el=new EagerLoading();
//el.EagerLoadingCollection();
//el.EagerLoadingCollectionAfterSession();
//---------------------------------------------------
LazyLoading lz = new LazyLoading();
lz.LazyLoadingCollection();
lz.LazyLoadingCollectionAfterInitialization();
lz.LazyLoadingCollectionAfterSession();
//---------------------------------------------------
//---------------------------------------------------
//---------------------------------------------------
//---------------------------------------------------
//---------------------------------------------------
//---------------------------------------------------
Console.ReadKey();
}
}