Clean way to get related entities based on selection
I am using C# and EF 4. I have a Actor repository. The entity Actor has many to many relationship with Movie. So in the ActorReposity i'd like to have a method example GetActors whose salary is greater than 100 and also in the results i would like to include the movies that this actor has been in whose director is Doe.(director is property on the movie) the signiture of the metho开发者_StackOverflow中文版d i have in the repository is IQueryable GetActors(). In this case i am just simpifying the signiture, After i get this to work then i can refactor to pass in parameters.
public class ActorRepository
{
public List<Actor> GetActors(int minimumSalary, string directorName)
{
return _ctx.Actors
.Include("Movies")
.Where(x => x.Salary > minimumSalary)
.Select(x => new
{
Actor = x,
Movies = x.Movies.Where(y => y.DirectorName == directorName)
})
.ToList()
.Select(x => new Actor
{
// copy scalar properties from anon to Actor, e.g:
ActorName = x.ActorName,
// then set the Movies navigational property to the filtered type
Movies = x.Movies
}).ToList()
}
}
精彩评论