I need to load a property on an object that is set for lazy load. When I try to access it or load it using NhibernateUtil.Initialize(), I get the same error:
“Initializing[ProjectName.Logic.Entities.AddressList#9]-Could not initialize proxy – no Session.”
I can ensure that the session DOES exist by calling the necessary method to open a session in the “using” clause. (We have buried our session creation such that instantiating a repository object with a parameter of “true” will also create a session factory if needed and open a session. Verified with a breakpoint triggered at the “using” clause.)
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);
}
}
}
Detail Mapping:
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();
}
}
You need to attach your Mailings object to the session before you can initialize any properties on it. You would have to expose a method on your repository to do so, which would call:
That will then associate the entity (Mailings) with your session and then the call to NHibernateUtil.Initialize(Mailings.AddressList) should work.
However I would suggest re-considering why you need to do it this way and look at having coarser grained sessions (ie. open it earlier and close it later).