I am trying to filter the results from an explicit load in EntityFramework.
The explicit loading works when I do not apply any filter but it does not load results once the filter is applied.
Classes
public partial class Student
{
public int StudentId { get; set; }
public int CourseId { get; set; }
public string Name { get; set; }
public string Status { get; set; }
public virtual ICollection<Grade> Grades { get; set; }
}
public partial class Grade
{
public int GradeId { get; set; }
public string Value { get; set; }
public string Status { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
Fluent API Mapping
modelBuilder.Entity<Grade>()
.HasMany(e => e.Students)
.WithMany(x => x.Grades)
.Map(m => m.ToTable("StudentGrades").MapLeftKey("GradeId").MapRightKey("StudentId"));
Usage
This works and populates the student.Grades
property.
using (var context = new Model1())
{
context.Configuration.LazyLoadingEnabled = false;
var student = context.Students.Single(x => x.StudentId == 1);
context.Entry(student).Collection(x => x.Grades).Load();
}
The SQL that is generated looks like this:
SELECT
[Extent2].[GradeId] AS [GradeId],
[Extent2].[Value] AS [Value],
[Extent2].[Status] AS [Status]
FROM [dbo].[StudentGrades] AS [Extent1]
INNER JOIN [dbo].[Grades] AS [Extent2] ON [Extent1].[GradeId] = [Extent2].[GradeId]
WHERE [Extent1].[StudentId] = 1 // this is parameterized in the actual hit.
When I run this query I get the full results.
However, when I apply filtering and use the following line, it does not populate student.Grades
.
context.Entry(student).Collection(x => x.Grades).Query().Where(x => x.Status == "A").Load();
This line generates this query:
SELECT
[Extent2].[GradeId] AS [GradeId],
[Extent2].[Value] AS [Value],
[Extent2].[Status] AS [Status]
FROM [dbo].[StudentGrades] AS [Extent1]
INNER JOIN [dbo].[Grades] AS [Extent2] ON [Extent1].[GradeId] = [Extent2].[GradeId]
WHERE ([Extent1].[StudentId] = 1) AND ('A' = [Extent2].[Status])
//the "1" is parameterized in the actual hit.
When I run this manually against the DB I get the correctly filtered results within SQL Server. The problem is that this doesn't populate student.Grades
in the C# object.