entity framework - Many to Many Relationship EF Code First -
entity framework - Many to Many Relationship EF Code First -
i'm starting larn mvc , i'm trying create database using entity framework code first approach. have table students , table of subjects, each pupil can have number of subjects , a subject can have number of students. linker table has column grade, because each pupil have different grade every subject. i'm getting error when trying create dtabase, telling me 1 or more validation errors detected during model generation. here models.
public class course of study { [key] public int courseid { get; set; } public string coursename { get; set; } public list<student> students { get; set; } } public class pupil { [key] public int studentid { get; set; } public string name { get; set; } public list<course> courses { get; set; } } public class studentcourses { [key] public course of study course { get; set; } [key] public pupil student { get; set; } public double grade { get; set; } } public class coursedb: dbcontext { public dbset<course> courses { get; set; } public dbset<student> students { get; set; } public dbset<studentcourses> studentcourses { get; set; } }
i've googled around bit , have seen approaches many many relationship, none have property in linker table( grade property).
unfortunately, if utilize intermediary table additional properties (or really, if define specific class manage relationship instead of letting ef handle automatically), lose ability have direct navigation property.
you'll have alter models to:
public class course of study { ... public list<studentcourses> students { get; set; } }
and
public class pupil { ... public list<studentcourses> courses { get; set; } }
then, example, if you're iterating through list of courses particular student:
@foreach (var course of study in student.courses) { @course.course.coursename, @course.grade }
also, worth mentioning might lead 1+n queries, if you're going should eagerly load course of study when querying student:
var pupil = db.students.include('courses.course').singleordefault(m => m.studentid == id);
edit
you had multiple problems here. caught first one, , stopped there without paying attending else might wrong. you're still getting errors because you're using composite key (combination of pupil , course of study foreign keys) on intermediary table. that's fine, when specify multiple keys, have specify column order:
[key, column(order = 0)] public course of study course { get; set; } [key, column(order = 1)] public pupil student { get; set; }
i'm not sure if can utilize key
navigation property. never tried myself, may work. if still errors, seek explicit foreign key properties:
[key, column(order = 0)] public int courseid { get; set; } public course of study course { get; set; } [key, column(order = 1)] public int studentid { get; set; } public pupil student { get; set; }
entity-framework ef-code-first
Comments
Post a Comment