我需要在设置为延迟加载的对象上加载属性。当我尝试使用 NhibernateUtil.Initialize() 访问或加载它时,我得到了同样的错误:
“正在初始化 [ProjectName.Logic.Entities.AddressList#9] - 无法初始化代理 - 没有会话。”
我可以通过调用必要的方法在“使用”子句中打开会话来确保会话确实存在。(我们已经隐藏了会话创建,因此使用“true”参数实例化存储库对象还将在需要时创建会话工厂并打开会话。通过在“使用”子句触发的断点进行验证。)
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();
}
}