Reputation: 5199
I have two classes. Both classes have similar structure in that they both have a many-to-many relation. But strangely enough the second class is causing a LazyInitializationException
. I've no clue why? Both are fetching data from an intermediate table but how come the second class is only producing the error?
public class TaskMap : VersionedClassMap<Task>
{
public TaskMap()
{
Id(x => x.TaskId);
Map(x => x.Subject).Not.Nullable();
Map(x => x.StartDate).Nullable();
Map(x => x.DueDate).Nullable();
Map(x => x.DateCompleted).Nullable();
References(x => x.Status, "StatusId");
References(x => x.Priority, "PriorityId");
References(x => x.CreatedBy, "CreatedUserId");
HasManyToMany(x => x.Users)
.Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
.Table("TaskUser")
.ParentKeyColumn("TaskId")
.ChildKeyColumn("UserId");
HasManyToMany(x => x.Categories)
.Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
.Table("TaskCategory")
.ParentKeyColumn("TaskId")
.ChildKeyColumn("CategoryId");
}
}
and
public class LocationMap: VersionedClassMap<Location>
{
public LocationMap()
{
Id(x => x.LocationId);
Map(x => x.Name).Not.Nullable();
Map(x => x.Address).Nullable();
Map(x => x.City).Nullable();
Map(x => x.State).Nullable();
Map(x => x.Country).Nullable();
Map(x => x.Pincode).Nullable();
HasManyToMany(x => x.Departments)
.Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
.Table("LocationDepartment")
.ParentKeyColumn("LocationId")
.ChildKeyColumn("DepartmentId"); //.Fetch.Join(); Adding this removes the error
}
}
EDIT:
Here is the link for the project.
Upvotes: 1
Views: 4217
Reputation: 417
You didn't supply any code how you use it with ISession, but such exception occurs when you trying to read uninitialized lazy property/collection on entity associated with closed session. Keep session alive until you work with entities.
UPDATE
I cannot figure out in a reasonable time where and when session is closed. The best you can do is to use eager loading in your queries. Here's an example for LocationController:
public IEnumerable<Location> Get()
{
return _session
.QueryOver<Data.Model.Location>()
.Fetch(x => x.Departments).Eager
.List()
.Select(_locationMapper.CreateLocation);
}
Upvotes: 2