如何编写 Func返回拥有最多孩子的实体?
我有一个访问我的实体框架的存储库。我有一个如下所示的方法:
public TEntity FindOne(Expression<Func<TEntity, bool>> criteria)
{
var query = _queryAll.Where(criteria);
return query.FirstOrDefault();
}
我有 2 个具有一对多关系的实体。我们称它们为课程
和学生
。一门课程
可以有多个学生
。我想编写一个查询来返回拥有最多学生的课程。
Courses.OrderByDescending(x=>x.Students.Count()).FirstOrDefault();
但我该如何将其写为 Func
呢?
我希望不是
(x=>x.OrderBy(y=>y.Students.Count()).FirstOrDefault().id == x.id)
因为添加另一个标准看起来不起作用:
(x=>x.OrderBy(y=>y.Students.Count())
.FirstOrDefault().id == x.id
&& x.CourseName == "CS101")
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")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根本不清楚为什么你要把
&& x.Course == "CS101"
最后。这到底是什么意思?我强烈怀疑问题出在您试图将所有内容都塞进FindOne
方法中的单个Where
子句的设计中。很简单,并非所有事情都可以轻松地以这种方式表达。另外,您应该使用
OrderByDescending
,以便第一个结果包含最多的学生。除此之外,就整体查询而言,使用排序对我来说似乎相当合理 - 但它不会完全适合您的
FindOne
方案。编辑:这是一个比只需要两个条件更大的问题。您可以写:
...但问题是,无论如何,您都必须能够访问
课程
,我想您正在尝试这样做远离。除此之外,它应该可以工作,但它很奇怪。如果您可以访问课程,您不妨忽略
FindOne
并自己编写查询:这显然比第一个版本更简单。
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 singleWhere
clause in yourFindOne
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:
... 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:That's clearly simpler than the first version.