How do I write a Func<T, bool> to return the entity with the most children?
I have a repository accessing my Entity Framework. I have a method that looks like开发者_开发知识库 this:
public TEntity FindOne(Expression<Func<TEntity, bool>> criteria)
{
var query = _queryAll.Where(criteria);
return query.FirstOrDefault();
}
I have 2 Entities that have a one to many relation. Lets call them Courses
and Students
. A Course
can have multiple Students
. I'd like to write a query that returns the Course that has the most students.
Courses.OrderByDescending(x=>x.Students.Count()).FirstOrDefault();
But how would I write that as a Func<T, bool>
?
I hope it's not
(x=>x.OrderBy(y=>y.Students.Count()).FirstOrDefault().id == x.id)
Because adding another criteria looks like it wouldn't work:
(x=>x.OrderBy(y=>y.Students.Count())
.FirstOrDefault().id == x.id
&& x.CourseName == "CS101")
It's not at all clear why you'd put the && x.Course == "CS101"
at the end. What is that even meant to mean? I strongly suspect the problem is in your design of trying to cram everything into a single Where
clause in your FindOne
method. Quite simply, not everything can easily be expressed that way.
Also, you should be using OrderByDescending
so that the first result has the most students.
Other than that, using ordering seems fairly reasonable to me, in terms of the overall query - but it won't fit neatly into your FindOne
scheme.
EDIT: This is a bigger problem than just requiring two conditions. You could write:
x => x.CourseId == "CS101" &&
x.Students.Count() == Courses.Where(x => x.CourseId == "CS101"))
.Max(x => x.Students.Count())
... but the problem is that at that point you've got to have access to Courses
anyway, which I'd imagine you're trying to get away from. Aside from that, it should work but it's grotesque.
If you can get access to courses, you might as well ignore FindOne
and write the query yourself:
var course = courses.Where(course => course.CourseId == "CS101")
.OrderByDescending(course => course.Students.Count())
.FirstOrDefault();
That's clearly simpler than the first version.
精彩评论