Getting this error for the orderby in where clause. I did this because previously, if I didn't define 'people' I'd get an error on the return for people saying the name 'people' doesnt exist in this current context. How do I fix this?
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);
}
Because there is indeed no such method. There is one on that accepts an IQueryable<T>
though. Use
IQueryable<Person> people;
or whatever element type would be appropriate.
OrderByDescending()
is an extension method of IQueryable<T>
, not of the non-generic IQueryable
.
So you need to declare people
as IQueryable<Person>
.
As mentioned several times you'd need to declare people
as an IQueryable<Person>
or whatever the type returned from the People
table is. If you want to use implicit typing you could rearrange your code as so:
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)
}
using System.Linq;
at the begining of the code file.IQueryable people;
to IQueryable<Person> people;
All
as birthyear
value you will get an exception when you reach var NumericYear = Convert.ToInt32(birthyear);
I suggest to change the whole function to this
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With