Search code examples
asp.netlinqentity-framework-core.net-6.0

How to get data from a table matched with a list in asp.net linq?


I have a database table AdvisorComments where I have advisorID and studentID along with other columns. There can be multiple records for same advisorID and studentID. Also, an advisorID can have different studentIds and vice versa.

I have another table Students where I have stored only current advisorId which can be updated to different advisor.

I want to get all the students (current: Students table; previous: AdvisorComments table) for a particular advisor from Students table.

Here's what I have tried:

this.advisorID = 1;
var advisorComments = _context.AdvisorComments.Where(x => x.advisorID == this.advisorID).GroupBy(x=>x.studentID).Select(m => new { m.First().studentID}).ToList();

/* output:
0: studentID 1
1: studentID 4
*/
var studentList = _context.Students.Where(x => x => x.advisorID == this.advisorID || advisorComments.Any(a => a.studentID== x.studentID)).ToList();

/*output:
Getting error

System.InvalidOperationException: 'The LINQ expression 'a => a.studentID == EntityShaperExpression: 
    Project.Models.Student
    ValueBufferExpression: 
        ProjectionBindingExpression: EmptyProjectionMember
    IsNullable: False
.studentID' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'.
*/

Solution

  • Declared advisorComments as List type and it's working.

    List<int> advisorComments = _context.AdvisorComments.Where(x => x.advisorID == this.advisorID).Select(m => studentID).Distinct().ToList();