I’m working with EF5 and I have a generic repository with a GetById method that can receive the include properties wanted like this one:
public virtual T GetByIdIncluding(long id, params Expression<Func<T, object>>[] includeProperties)
{
IQueryable <T> query = DbContext.Set<T>().Find(id) as IQueryable<T>;
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query.FirstOrDefault();
}
DbContext.Set<T>().Find(id) return the correct object, but when I cast it with as IQueryable then the value of variable query becomes null.
Why? How can I select only the entity with the Id sent by parameter and all the includings sent by parameter?
Example of usage:
var houses = Uow.Types.GetByIdIncluding(id, tt => tt.Houses);
Thanks in advance! Guillermo
DbContext.Set<T>().Find(id)returns single entity.IQueryable<T>is aDbContext.Set<T>().You can’t include some properties after you selected single entity by id. Also you can’t use
DbSet<T>.Findafter you included some properties, because result will beIQueryable<T>. What you can do – include properties and filter result by id later:And later:
Also you can create method
GetByIdIncludingin your concrete repository classes (not in generic repository):BTW consider using lazy-loading (it’s enabled by default).