'IQueryable'不包含'OrderByDescending'的定义

时间:2015-12-11 14:54:23

标签: c# .net linq iqueryable

在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);
 }

4 个答案:

答案 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)

  1. 您必须在代码文件的开头有using System.Linq;
  2. 您应该将IQueryable people;更改为IQueryable<Person> people;
  3. 如果您将此方法称为All作为birthyear值,则会在到达var NumericYear = Convert.ToInt32(birthyear);
  4. 时收到异常
  5. 我建议将整个功能更改为

    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);
        }
    }