1

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 base.ObjectSet.Where(x => x.Users ?????
}
Community
  • 1
  • 1
dan
  • 5,664
  • 8
  • 45
  • 59

1 Answers1

4

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();
dan
  • 5,664
  • 8
  • 45
  • 59