【发布时间】:2021-08-24 11:20:04
【问题描述】:
我正在使用连接到 PostrgreSQL 13 的 EF Core 5.0。我正在尝试有条件地将 OrderBy() 和 Take() 添加到这样的查询中:
public IEnumerable<Person> GetPeople(int age, int limitCount)
{
IQueryable<Person> peopleQuery = _context.people.Where(p => p.Age == age);
if (limitCount > 0)
peopleQuery.OrderBy(p => p.DateAddedUTC).Take(limitCount);
System.Diagnostics.Debug.WriteLine(peopleQuery.ToQueryString());
return peopleQuery;
}
不管limitCount的值是多少,我的结果都没有限制或排序; ToQueryString() 返回:
SELECT p.id, P.name, P.age
FROM people AS p
WHERE (p.age = @__age_0))
但是如果limitCount > 0,我想要这样的东西:
SELECT p.id, P.name, P.age
FROM people AS p
WHERE (p.age = @__age_0))
ORDER BY p.date_added_utc
LIMIT @__p_1
我认为 linq 查询可以像这样组合。我什至尝试过ToList() 看看是否可以解决问题,但没有任何改变。
如何在不重复代码的情况下实现我的目标?
【问题讨论】:
标签: c# linq entity-framework-core