Question for Linq users out there: I’m getting an InvalidCastexception: Specified cast is not valid whenever I try to obtain an IEnumerable from revs after making the Linq query. There database is populated and it should be returning values.
Specifically, the error is occurring on the line List<PDP> rev = revs.ToList<PDP>();
Any ideas what’s going on?
short ret;
using (DataContext db = new DataContext())
{
var play = from p in db.PDP
where p.ID == id
select p;
var revs = play.OrderByDescending(p => p.revision);
List<PDP> rev = revs.ToList();
var revNum = revs.ToList().Count() > 0 ? rev.First().revision : 0;
ret = (short)revNum;
}
EDIT
I’ve clarified some parts of the code.
EDIT 2
rev exists as a debugging variable to narrow down where the error was.
The original code was:
short ret;
using (GasForecastDataContext db = new GasForecastDataContext())
{
var play = from p in db.PDP
where p.Play_ID == play_id
select p;
var revs = play.OrderByDescending(p => p.revision);
var revNum = revs.Count > 0 ? rev.First().revision : 0;
ret = (short)revNum;
}
Is there a specific reason you’re declaring the “rev” list variable at all? “Count()” and “First()” are available on IEnumerable interface ( “revs” ).