我需要在为延迟加载设置的对象上加载属性。当我尝试访问它或使用NhibernateUtil.Initialize()加载它时,我得到相同的错误:
“正在初始化[ProjectName.Logic.Entities.AddressList#9] - 不能初始化代理 - 没有会话。”
通过调用必要的方法在“using”子句中打开会话,我可以确保会话存在。 (我们已经埋没了会话创建,因此实例化参数为“true”的存储库对象也会在需要时创建会话工厂并打开会话。使用“using”子句触发的断点进行验证。)
foreach (MemberViewModel MVM in _filteredMemberViewModels)
{
foreach (Detail Mailings in MVM.Member.Mailings)
{
//used for lazy loading
using (var repo = new AddressListRepository(true))
{
NHibernateUtil.Initialize(Mailings.AddressList);
}
}
}
详细信息映射:
public class DetailMap : ClassMap<Detail>
{
public DetailMap()
{
Table("AddressDetailsCCN");
// Unique Identifier
Id(x => x.Id, "Id")
.GeneratedBy.Identity();
// MANY TO ONE relationship (the list has many details)
References<AddressList>(x => x.AddressList, "ListId")
.LazyLoad()
.Not.Nullable()
.Cascade.None();
// MANY TO ONE relationship (Members have details)
References<Member>(x => x.Member, "MemberId")
.Not.LazyLoad()
.Not.Nullable();
// First line of Address
Map(x => x.Address, "Address")
.Nullable();
// Second line of Address
Map(x => x.Address2, "Address2")
.Nullable();
// City
Map(x => x.City, "City")
.Nullable();
// State
Map(x => x.State, "State")
.Nullable();
// Zip
Map(x => x.Zip, "Zip")
.Nullable();
// Finalized date
Map(x => x.FinalizedDate, "FinalizedDate")
.CustomType(typeof(DateTime))
.Nullable();
// Date the list is created by
Map(x => x.CreatedDate, "CreatedDate")
.CustomType(typeof(DateTime))
.Not.Nullable();
}
}
答案 0 :(得分:2)
您需要先将Mailings对象附加到会话,然后才能初始化其上的任何属性。您必须在存储库中公开一个方法来执行此操作,该方法将调用:
session.Lock(entity, LockMode.None);
然后将实体(Mailings)与您的会话相关联,然后调用NHibernateUtil.Initialize(Mailings.AddressList)应该有效。
但是我会建议你重新考虑为什么你需要这样做,看看有更粗粒度的会话(即先打开它然后再关闭)。