开发者

Linq results to IEnumerable invalid cast

开发者 https://www.devze.com 2023-03-14 22:15 出处:网络
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 po

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开发者_JS百科'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" ).

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

    ret = (short) revs.Count() > 0 ? revs.First().revision : 0;
}


It seems like the elements in db.PDP are some type other than PDP, or if it is PDP, it may be in another namespace.


Wouldn't it still be an IQueryable?

rev could probably be cast as an IEnumberable, but revs is probably still IQueryable.

You might be able to call ToList() on revs.


Try this:

List<PDP> rev = revs.ToList<PDP>();

I just added the type for the generic.

0

精彩评论

暂无评论...
验证码 换一张
取 消