我在C#中遇到以下异常:
InvalidCastException:无法从类型转换 ' System.Collections.Generic.List`1 [MyProj.Data.Entities.Student]'至 键入' MyProj.Data.Access.IStudent'。
我的项目编译成功。我有两个对象定义如下:
public interface IStudent
{
long ID { get; set; }
string SystemCode { get; set; }
string FirstName { get; set; }
string LastName { get; set; }
DateTime DateOfBirth { get; set; }
}
public class Student : IStudent
{
public long ID { get; set; }
public string SystemCode { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
public interface ICourseRequest
{
long ID { get; set; }
long StudentID { get; set; }
int CourseID { get; set; }
int? FacultyID { get; set; }
DateTime StartDate { get; set; }
DateTime CreationDate { get; set; }
IStudent Student { get; set; }
}
public class CourseRequest : ICourseRequest
{
public long ID { get; set; }
public long StudentID { get; set; }
public int CourseID { get; set; }
public int? FacultyID { get; set; }
public DateTime StartDate { get; set; }
public DateTime CreationDate { get; set; }
public IStudent Student { get; set; }
}
我正在使用SQLtoLinq来检索我的数据(来自SQL Server),如下所示:
IList<ICourseRequest> result = _database.course_requests.Select(a => new CourseRequest
{
CreationDate = a.crsreq_create_date,
StartDate = a.crsreq_start,
FacultyID = a.crsreq_faculty,
ID = a.crsreq_id,
CourseID = a.crsreq_crs,
StudentID = a.crsreq_student,
Student = _database.students.Where(p => p.stud_id == a.crsreq_student)
.Select(s => new Student
{
ID = p.stud_id,
DateOfBirth = s.stud_dob,
FirstName = s.stud_fname,
LastName = s.stud_lname,
SystemCode = s.stud_sys_code
}).SingleOrDefault(),
}).ToList<ICourseRequest>();
为什么在项目成功编译时会在运行时抛出此强制转换异常?
答案 0 :(得分:1)
这非常奇怪。在整个项目中(我和其他对象)一直在这样查询,只是这给了一个错误。
我通过将其转换为IStudent
来修复它。我不知道为什么简单的SingleOrDefault
不起作用。任何人都可以解释原因吗?
这就是修正它的原因:
IList<ICourseRequest> result = _database.course_requests.Select(a => new CourseRequest
{
CreationDate = a.crsreq_create_date,
StartDate = a.crsreq_start,
FacultyID = a.crsreq_faculty,
ID = a.crsreq_id,
CourseID = a.crsreq_crs,
StudentID = a.crsreq_student,
Student = _database.students.Where(p => p.stud_id == a.crsreq_student)
.Select(s => new Student
{
ID = p.stud_id,
DateOfBirth = s.stud_dob,
FirstName = s.stud_fname,
LastName = s.stud_lname,
SystemCode = s.stud_sys_code
}).SingleOrDefault() as IStudent, //<-- This is what fixed it
}).ToList<ICourseRequest>();