简体   繁体   中英

Entity framework fluent API on already existing data

Model1)

public class Student {

    int StudentID {get;set;}

    string FirstName {get;set;}

    string LastName {get;set;}

ICollection courses = {get; set;}

}

Model2)

public class Course{

    int CourseID {get;set;}

    string CourseName {get;set;}

    int CreditHours {get;set;}

}

Model3)

public class StudentCourse{

    int StudentCourseID {get;set;}

    int StudentID {get;set;}

    int CourseID {get;set;}

}

Now I add a bunch of data to the database...

and the relationship between student to course (one to many) is lost.

That is now I only have three data tables based on the models above in the database

with no relationship between them whatsoever.

If I create another application, write 3 models matching exactly as the models above and define the one to many relationship between

student and course using fluent API, will that work? That is will I be able to relate the data that already exists?

For example,

After doing the step above and querying a list of student and doing student.courses.ToList(); will the courses with matching studentID be returned as a list with that query?

and the relationship between student to course (one to many) is lost.

The relationship isn't working because you're only setting a link on the Student side of it. You also need to add an endpoint for the relationship on Courses :

public class Student {
    public virtual ICollection<Course> Courses { get; set; }
}

public class Course {
    public virtual Student Student { get; set; }
}

This should set up the 1-many relationship.

many students take the same courses though, so I'd set it up as a many-many relationship:

public class Student {
    public virtual ICollection<Course> Courses { get; set; }
}

public class Course {
    public virtual ICollection<Student> Students { get; set; }
}

I believe that this should eliminate the need for the StudentCourse table, but I stand under correction on this point.

Now, for your link between them (StudentCourse), you'll want to properly structure your relationships on this one, too:

public class StudentCourse
{
    public int Id { get; set; }
    public virtual Student Student { get; set; }
    public virtual Course Course { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM