Reputation: 5634
I'm using Entity Framework 7 RC1, I am essentially trying to create a field so that I can hold Students Standards (one student can have many standards, each standard can belong to many students). Following the asp.net docs I have the tables setup, and I filled out the Student table, the Standard table and StudentStandard table manually in SQL Server using some made up data. However, when I debug the code/view during runtime I see that the StudentStandards field is 'null' when I perform a getAll in the controller. I am accessing this field in the view using the following code: model.Students.StudentStandards.Select(c=>c.StandardId) but this doesn't provide anything.
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime DateOfBirth { get; set; }
public byte[] Photo { get; set; }
public decimal Height { get; set; }
public float Weight { get; set; }
public ICollection<StudentStandard> StudentStandards { get; set; }
}
public class StudentStandard
{
[ForeignKey("Student")]
public int StudentId { get; set; }
public Student Student { get; set; }
[ForeignKey("Standard")]
public int StandardId { get; set; }
public Standard Standard { get; set; }
}
public class Standard
{
public int StandardId { get; set; }
public string StandardName { get; set; }
public ICollection<StudentStandard> StudentStandards { get; set; }
}
This is what the table look like after using migrations to create it:
My question: how do I get this m:m relationship to store and retrieve this data?
Upvotes: 0
Views: 163
Reputation: 5634
I had to eager-load the table using the following code:
context.Students
.Include(a => a.StudentStandards)
.ThenInclude(b => b.Standard);
Upvotes: 0
Reputation: 35460
What you're after is called eager-loading. By default, any EF query will fetch the records of the entity itself, but not of the foreign key tables that belong to it. If you're interested in bringing in the related tables data, you should use Include()
function and specify the foreign key tables you are interested in, the Standards table in your case. Your EF Linq will look something like this:
//context is your DbContext object
context.Students.Include(s => s.Standards).ToList();
Upvotes: 1