How can I perform complex queries (eg. over many-to-many relationship) in Entity Framework using a repository pattern?
I am using Entity Framework v4 and the repository pattern found in the answer to this SO question:
Advantage of creating a generic repository vs. specific repository for each object?
Namely, each repository inherits from an abstract base class that contains generic methods like add, delete, etc. and also implements a specific repository interface for any methods that are unique to that repository/entity.
ie.
public class CompanyRepository : Repository<Company>, ICompanyRepository {
public Company Get(int id)
{
return base.ObjectSet.SingleOrDefault(x => x.Id == id);
}
}
How can I perform more complex queries that reference entities that are not part of this repository... (say across a many-to-many relationship to another table)?
public List<Company> GetAllCompaniesForUser(int userId)
{
return bas开发者_运维问答e.ObjectSet.Where(x => x.Users ?????
}
I think this may be the way to do it:
return base.ObjectSet.Where(x => x.Users.Any(u => u.Id == userId)).ToList();
or
var companies = from c in base.ObjectSet
from u in c.Users
where u.Id == userId
select c;
return companies.ToList();
精彩评论