Reputation: 4265
I have turned off lazy loading and the proxy creation on my DbContext. I am employing the Repository partern and UnitOfWork. My UnitOfWork inherits from DBConext. Here is an example of what I am doing:
public class User
{
public Guid Id {get;set;}
public virtual Guid UserTypeId {get;set;} //foreign key to UserType and setup in the EF fluent mappings and it does load if I am using lazy loading.
public virtual UserType {get;set;}
}
public class UserType
{
public Guid Id {get;set;}
public string Name {get;set;}
}
This is inside my UoW:
public IDbSet<TEntity> CreateSet<TEntity>() where TEntity : class
{
return base.Set<TEntity>();
}
I query the context via my Repository:
protected Expression<Func<TEntity, object>>[] Includes;
public IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> criteria, params Expression<Func<TEntity, object>>[] includes)
{
Includes = includes;
return GetSet().Where(criteria)
.AsEnumerable();
}
public IDbSet<TEntity> GetSet()
{
var set = _unitOfWork.CreateSet<TEntity>();
if(Includes != null)
{
foreach (var include in Includes)
{
set.Include(include);
}
}
return set;
}
So, as you can see I am passing in an array of expressions to be included in my query. So I might call it like this:
var users = userRespository.Get(u => u.Id == SomeGuid, u => u.UserType);
The UserType is not being included in the query and I don't know what. Should I be calling something other than Set on the DbContext?
Update:
I am thinking before I call the base.Set I would need to add the includes there. Not sure though.
Upvotes: 4
Views: 4652
Reputation: 364249
All extensions methods on IQueryable
usually works in the way that they produce a new IQueryable
so you must assign it if you want to get the effect:
public IDbSet<TEntity> GetSet()
{
var set = _unitOfWork.CreateSet<TEntity>();
if(Includes != null)
{
foreach (var include in Includes)
{
set = set.Include(include);
}
}
return set;
}
Btw. it looks quite similar to my older solution.
Upvotes: 5