使用分离的对象按需加载延迟集合

时间:2012-05-22 19:51:35

标签: nhibernate lazy-loading

我正在学习nHibernate,当我使用lazy collections / object时遇到麻烦。

假设以下域名:

Class Author
 public virtual int Id {get;set;}
 public virtual IList<Books> Books{get;set;}

class Books
 public virtual int Id {get;set;}
 public virtual string Name {get;set;}

我使用session.load加载作者的实体......然后关闭会话。像这样:

public static IList<T> GetAllClosingSession<T>()
{

  IList<T> aList;
  using (ISession s = OpenSession())
  {
    aList = s.CreateCriteria(typeof (T)).List<T>();
  }
  return aList;
}

在此之后,作者被解除了。

当我尝试使用de Books集合(anAuthor.Books.Add(aBook))时会抛出一个LazyInitializationException。我理解这种行为,因为Author对象是dettached。

我想向实体(作者)注入加载它的SessionFactory。当我调用惰性对象时,它使用注入的sessionFactory并继续加载(将数据库附加到对象并执行nHibernateUtil.Initialize(aProxy))

总结: 我希望得到“透明加载”的相同行为,但是有一个脱离的对象。

我必须使用绑定到不同数据库的对象。

我希望你理解我。

任何建议都会很好。 提前谢谢。

编辑:

在我的项目中,我使用连接数据注入每个创建的模型类(因此每个对象都知道如何连接到数据库),并且可以使用它来处理DAO / Repository。我使用这个函数创建每个对象。所以不要做MyClass myClass = new MyClass();我做MyClass myClass = MyCustomFactory.CreateModelObject();

public T CreateModelObject<T>()
{
    if (_connection == null)
    throw new NullReferenceException("you must assign a connection to this factory");
    Type[] types = new Type[] { };
    object[] parametros = new object[] { };
    // Get the Constructor
    ConstructorInfo constructor = typeof(T).GetConstructor(types);
    // Instantiate the object
    T theObject = (T)constructor.Invoke(parametros);
    // Get the property ConnectionData
    PropertyInfo propertyInfo = typeof(T).GetProperty("ConnectionData");
    // Assign a previosly connection data object to ConnectionData Property
    propertyInfo.SetValue(theObject, _connData, null);

    return theObject;
}

0 个答案:

没有答案