Let\'s say I have the model: public class Student { int StudentID {get;set;} str
ID: 3858478 • Letter: L
Question
Let's say I have the model:
public class Student {
int StudentID {get;set;}
string FirstName {get;set;}
string LastName {get;set;}
ICollection courses = {get; set;}
}
Another Model:
public class Course{
int CourseID {get;set;}
string CourseName {get;set;}
string CreditHours {get;set;}
}
One more Model
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 it return the list of courses for the particular student based on what is in the database already?
Explanation / Answer
Fluent API is another way to configure your domain classes.
It can provide more functionality for configuration than DataAnnotations( Ex: Key).
Fluent API should be in OnModelCreating method
You can configure all domain classes in DbModelBuilder because, at this point, all your domain classes would have initialized
public class StudentCourse: DbContext
{
public StudentCourse(): base()
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Course> Standards { get; set; }
public DbSet<StudentCourse> Students { get; set; }
}
You can make the primary key and relationships using Fluent API. The following example will explain the how to configure Relationship
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.