c# - Linq Select causes InvalidCastException -
var courses = db.courses.select(course => new model.course() { dates = db.dates .where(date => date.courseid == course.id) .select(date => date._date.tostring()) .tolist() }); return courses.tolist();
the return call causes system.invalidcastexception
. if remove dates, there no error.
here's course class:
public class course { public list<string> dates { get; set; } }
screenshot vs:
the .tostring()
on _date
column causing invalidcastexception. linq sql trying convert _date
string using tostring() not exist in sql. need grab date sql , convert string in memory.
try this:
// grab db list of courses , dates. // put dates in list of datetime, can use datetime2. // note courses iqueryable. var courses = db.courses.select(course => new list<datetime> { dates = db.dates .where(date => date.courseid == course.id) .select(date => date._date).tolist() }); // extract data sql calling our iqueryable's tolist() of method. puts data list in memory. // using list.select() method, convert dates strings. return ienumerable. // convert resulting ienumerable list. return courses .tolist() .select(course => new model.course { // here, using .net framework's datetime.tostring() // can use formatting options available that. dates = course.dates.select(date => date.tostring()).tolist() }) .tolist();
Comments
Post a Comment