One good practice when using
an ORM mapper which supports lazy loading is to tell from the start what you know you will need, and
lazy load what will be needed only under some circustances. This requires constant attention with how you write your code, but this is a good thing really and it makes things much more clear.
For example, we want to be able to say this to a
repository:
_criteria = _userRepository
.InitialiseListCriteriaForActiveAndInactive()
.WithClient()
.WithProfile()
.WithOperatorRole()
.GetCriteria();
This means: give me the active and inactive users with their associated clients, profiles and operator roles.
Here is a solution for that:
public class UserRepository
{
private ICriteria _criteria;
private UserRepository WithMembership()
{
_criteria.SetFetchMode("aspnetMembership", FetchMode.Eager)
.CreateAlias("aspnetMembership", "am");
return this;
}
private UserRepository OnlyApproved()
{
_criteria.Add(Expression.Eq("IsApproved", true));
return this;
}
public UserRepository WithClient()
{
_criteria.SetFetchMode("Clients", FetchMode.Eager)
.CreateAlias("Clients", "c", JoinType.LeftOuterJoin );
return this;
}
public UserRepository WithProfile()
{
_criteria.SetFetchMode("aspnetProfile", FetchMode.Eager)
.CreateAlias("aspnetProfile", "ap", JoinType.LeftOuterJoin);
return this;
}
public UserRepository WithOperatorRole ( )
{
_criteria.SetFetchMode ( "OperatorRole", FetchMode.Join )
.CreateAlias ( "OperatorRole", "or", JoinType.LeftOuterJoin );
return this;
}
public UserRepository InitialiseCriteriaFor(Guid userId)
{
_criteria = Repository<aspnetUser>.CreateCriteria()
.Add(new EqExpression("Id", userId));
return this;
}
public UserRepository InitialiseListCriteriaForActiveAndInactive()
{
_criteria = Repository<aspnetUser>.CreateCriteria();
return WithMembership();
}
public UserRepository InitialiseListCriteria()
{
_criteria = Repository<aspnetUser>.CreateCriteria();
return WithMembership().OnlyApproved();
}
public aspnetUser LoadUser()
{
return _criteria.UniqueResult<aspnetUser>();
}
public IList<aspnetUser> LoadList()
{
return _criteria.List<aspnetUser>();
}
public ICriteria GetCriteria()
{
return _criteria;
}
}