I have below two classes which represent my SQL tables (generated by ADO.net entity data model):
public partial class Parent
{
public Parent()
{
this.Students = new HashSet<Student>();
}
public int Parent_Id { get; set; }
public string Parent1_Last_Name { get; set; }
public string Parent1_First_Name { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public partial class Student
{
public int Student_Id { get; set; }
public string Student_Last_Name { get; set; }
public string Student_First_Name { get; set; }
public int Parent_Id { get; set; }
public virtual Parent Parent { get; set; }
}
Now I am trying to read the data from my tables in a method as below:
var parent = new Parent();
var students = new List<Student>();
using (var dc = new SchoolDataEntities())
{
students = dc.Students.Where(s => s.Parent_Id.Equals(parentId)).ToList();
parent = dc.Parents.Where(p => p.Parent_Id.Equals(parentId));
parent.Students = students;
}
I am getting a run-time "Invalid Cast" exception error when I reading from Parent
table (Students
table is working fine).
Error: System.InvalidCastException: 'Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[SchoolApplication.Parent]' to type 'SchoolApplication.Parent'.'
Someone please educate me what I was doing wrong?