I'm trying to create a generic GetAll method that works for each of my model classes in my ASP.NET MVC4 project.
Here's my code:
public static List<T> GetAll(params string[] includeProperties)
{
using (MovieSiteDb db = new MovieSiteDb())
{
var entities = db.Set<T>();
foreach (var includeProperty in includeProperties)
{
entities.Include(includeProperty);
}
return entities.ToList();
}
}
Now I call it the following way (Movie inherits the GetAll method):
Movie.GetAll("Category");
However I get an error when I try to access the foreign key "Category" in the view model. Why isn't it being included?
I can't say I've used EF myself, but in general LINQ doesn't mutate queries when you call a method - instead it returns a new query. So if you change your code to:
DbQuery<T> entities = db.Set<T>();
foreach (var includeProperty in includeProperties)
{
entities = entities.Include(includeProperty);
}
you may find that fixes the problem.
(The type of entities
is now fixed to DbQuery<T>
rather than using var
to implicitly type it to DbSet<T>
, as Include
returns DbQuery<T>
.)
See more on this question at Stackoverflow