Linq Select导致InvalidCastException

时间:2016-01-27 16:40:15

标签: c# linq

sum

返回致电会导致 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(); 。如果我删除日期,则没有错误。

这里的课程课程:

System.InvalidCastException

VS的截图:

enter image description here

2 个答案:

答案 0 :(得分:0)

您没有显示完整的模型,但我认为您应该加入这两个表格join,而不是where与此类似:

var courses = 
    db.Courses
    .Join(
        db.Dates, 
        c => c.ID, 
        d => d.CourseID, 
        (c, d) => new 
        { 
            Course = c, 
            Dates = d 
        }
    ).ToList();

答案 1 :(得分:0)

.ToString()列上的_Date可能导致InvalidCastException。 Linq to SQL尝试使用ToString()将_Date转换为字符串,这在SQL中不存在。您需要简单地从SQL中获取日期并转换为内存中的字符串。

试试这个:

// Grab from db list of courses and their dates. 
// Put dates in a List of DateTime, but you can also use DateTime2.
// Note that courses will be an 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 from SQL by calling our IQueryable's ToList() of method. This puts the data as a List in memory.
// Using the List.Select() method, convert dates to strings. This will return an IEnumerable.
// Convert the resulting IEnumerable back to a List.
return courses
          .ToList()
          .Select(course => new Model.Course
          {
             // Here, you are using the .NET Framework's DateTime.ToString()
             // So you can use any formatting options available with that.
             Dates = course.Dates.Select(date => date.ToString()).ToList()
          })
          .ToList();