在where子句中获取orderby的此错误。我之所以这样做,是因为之前,如果我没有定义'人',我会在返回时收到错误,因为人们说这个名字'人'在当前的情境中并不存在。我该如何解决这个问题?
public JsonResult PersonsList(string birthyear)
{
TutorialDBContext db = new TutorialDBContext();
var NumericYear = Convert.ToInt32(birthyear);
IQueryable people;
if (birthyear == "All")
{
people = from m in db.persons
select m;
people = people.OrderByDescending(s => s.birthdate);
}
else
{
people = from m in db.persons
where m.birthdate.Year >= NumericYear
where m.birthdate.Year <= (NumericYear + 9)
select m;
}
return Json(people, JsonRequestBehavior.AllowGet);
}
答案 0 :(得分:6)
因为确实没有这样的方法。虽然有一个接受IQueryable<T>
。使用
IQueryable<Person> people;
或任何适合的元素类型。
答案 1 :(得分:4)
OrderByDescending()
是 IQueryable<T>
的扩展方法,而不是非通用IQueryable
的扩展方法。
因此,您需要将people
声明为IQueryable<Person>
。
答案 2 :(得分:2)
如上所述,您需要将people
声明为IQueryable<Person>
或从People
表返回的类型。如果你想使用隐式类型,你可以重新排列代码:
var people = from m in db.persons
select m;
if (birthyear == "All")
{
people = people.OrderByDescending(s => s.birthdate);
}
else
{
people = people.Where(p => p.birthdate.Year >= NumericYear
&& p.birthdate.Year <= NumericYear + 9)
}
答案 3 :(得分:1)
using System.Linq;
。IQueryable people;
更改为IQueryable<Person> people;
All
作为birthyear
值,则会在到达var NumericYear = Convert.ToInt32(birthyear);
我建议将整个功能更改为
public JsonResult PersonsList(string birthyear)
{
using (var db = new TutorialDBContext())
{
IQueryable<Person> people;
if (birthyear == "All")
{
people = db.persons.OrderByDescending(s => s.birthdate);
}
else
{
var NumericYear = Convert.ToInt32(birthyear);
people = from m in db.persons
where m.birthdate.Year >= NumericYear
where m.birthdate.Year <= (NumericYear + 9)
select m;
}
return Json(people, JsonRequestBehavior.AllowGet);
}
}