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 singleWhereclause in yourFindOnemethod. Quite simply, not everything can easily be expressed that way.Also, you should be using
OrderByDescendingso 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
FindOnescheme.EDIT: This is a bigger problem than just requiring two conditions. You could write:
… but the problem is that at that point you’ve got to have access to
Coursesanyway, 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
FindOneand write the query yourself:That’s clearly simpler than the first version.