0

I have created a simple web api project using Entity Framework on AP.Net 2013. It performs basic CRUD. The project is connected to a SQL Server database with 2 tables - Students and Subjects. These two tables are connected with the Roll number being a PK in Students and FK in Subjects.

The project works fine when I am accessing only the Students. It gives me a NotSupportedException when I add the code to handle the subjects also.

I am running this app in the Fiddler.

My code is as below:

private StudentDBEntities db = new StudentDBEntities();

// GET: api/Student
public IList<SubjectDetailsDto> GetStudents()
{
    return db.Students.Select(s => new SubjectDetailsDto
    {
        Roll_Number = s.Roll_Number,
        FirstName = s.FirstName,
        LastName = s.LastName,
        Class = s.Class,
        Gender = s.Gender,
        subjects = s.subjects.ToList()
    }).ToList();
}

Can anyone tell me why the exception is occurring?

EDIT: SubjectDetailsDto.cs

public class SubjectDetailsDto
{
    public int Roll_Number { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Class { get; set; }
    public string Gender { get; set; }
    public List<Subject> subjects { get; set; }
}

I have added a snapshot of the exception: enter image description here

EDIT

Student.cs

    public partial class Student
    {
      public int Roll_Number { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public int Class { get; set; }
      public string Gender { get; set; }

      public ICollection<Subject> subjects { get; set; }
   }

Subject.cs

public partial class Subject
{
    public int Roll_Number { get; set; }
    public int English { get; set; }
    public int Mathematics { get; set; }
    public int Science { get; set; }
    public Nullable<int> Total { get; set; }

    //navigation property
    public Student student { get; set; }
}
Pallavi Prasad
  • 577
  • 2
  • 9
  • 28

1 Answers1

0

The root of the problem is the fact that Entity Framework doesn't know how to translate Enumerable.ToList() into SQL code that will load the data. The culprit line is this one:

subjects = s.subjects.ToList()

In order to avoid this you could join the tables or load the data in two separate requests:

var students = db.Students.Select(s => {}).ToList();
var studentIds = students.Select(s=>s.Id).ToArray();
var subjects = db.Subjects.Where(s=>studentIds.Contains(s.StudentId))
    .ToArray()
    .GroupBy(s=>s.StudentId)
    .ToDictionary(g=>g.Key, g=>g.ToList());
//Populate subjects for each student
students.ForEach(s=>
{
    s.subjects = subjects.ContainsKey(s.Id)?subjects[s.Id]:new List<Subject>();
});
RePierre
  • 9,358
  • 2
  • 20
  • 37