3

I am trying to get the number of subjects each student have using the below query:

var selectedSubject = context.Students
                             .Include(d => d.Subjects)
                             .Select(dr => new
                                           {
                                               Name = dr.Student.FirstName,
                                               NoOfSubject = dr.Subjects.Count
                                           })
                             .ToList();

But I am getting an exception

An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll

Additional information: The specified type member 'Subjects' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

2
  • Can you add the relevant parts of your Students and Subjects models? Commented Nov 21, 2014 at 13:01
  • We need to see your model definitions. EF is telling you that Subjects is not queryable. Commented Nov 21, 2014 at 13:11

2 Answers 2

2

You won't be able to access non entity member Properties on the IList interface (like Count) until the query is materialized.

Either materialize early:

var selectedSubject = context.Students
                         .Include(d => d.Subjects)
                         // .Where() goes here, 
                         .ToList()
                         .Select(dr => new
                                       {
                                           Name = dr.Student.FirstName,
                                           NoOfSubject = dr.Subjects.Count
                                       })
                         .ToList();

Or, make use of the Count() method, which will be mappable into Sql:

var selectedSubject = context.Students
                         .Include(d => d.Subjects)
                         .Select(dr => new
                                       {
                                           Name = dr.Student.FirstName,
                                           NoOfSubject = dr.Subjects.Count()
                                       })
                         .ToList();
Sign up to request clarification or add additional context in comments.

Comments

0

Have you tried this:

var count = context.Students.Select(x=>new { Name = x.Student.FirstName, 
    NoOfSubject = x.Subjects.SubjectId.Count}).ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.