nhibernate.在同一会话中创建后,Bag为空
本文关键字:Bag 为空 创建 会话 nhibernate | 更新日期: 2023-09-27 18:10:13
我有一个对象,它包含对象列表。
public class Product: IProduct
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<IFunction> Functions { get; set; }
}
public class Function : IFunction
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
public virtual IProduct Product { get; set; }
}
对象映射列表(IList
<bag name="Functions" cascade="all" table="T_WEBFUNCTIONS" lazy="false">
<key column="PRODUCT_ID" />
<one-to-many class="Function" />
</bag>
代码:
我尝试创建一个Product
的新对象 public IProduct SetProduct(string productName)
{
// Product repository, which have nhibernate opened session ( ISession )
IDBRepository<IProduct> rep = Repository.Get<IProduct>();
// Create new object of product
rep.Create(new Product() { Name = productName });
// get created object by name
prod = rep.Query().Where(x => x.Name == productName).SingleOrDefault();
// I HAVE ISSUE HERE
// prod.Functions == NULL. It must be a new List<Function>()
// Nhibernate don't create empty list for me and this property always null
return prod;
}
。当nhibernate会话关闭并再次打开时,该列表将被创建,并且有0个项目。
如果我在同一会话中创建一个对象(Product)并在创建后获取它,则bag将为空。
数据存储库功能
public class DBRepository<T> : IDBRepository<T>
{
protected ISession CurrentSession;
public DBRepository(ISession session)
{
CurrentSession = session;
}
public void Create(T obj)
{
var tmp = CurrentSession.BeginTransaction();
CurrentSession.Save(obj);
tmp.Commit();
}
}
当您调用new Product()
时,您的代码正在实例化一个对象,并且List<>属性开始为null。NHibernate帮不了你——这是你自己决定要做的(通过不覆盖默认的c'tor)。
NHibernate的第一级缓存(这里有简短的解释)在你提交事务时保存你的对象,所以当在同一个开放会话中,你通过对象的ID请求对象时,NHibernate跳过从数据库获取实体,并为你提供相同的实例化对象。您可以使用Object.ReferenceEquals(prodYouCreated, prodRetrievedFromRepository)
进行测试。
当你关闭会话时,第一级缓存被清除,下一次你查询NHibernate获取数据并自己构建对象-它选择给你一个零长度的列表,而不是null。这是默认行为。
希望这对你有帮助,
那么默契