Reputation: 117
I have two entities Student and Class. I've created the DB with Code First Entity Framework, and i want it to create a many-to-many relationship table.
public class Student
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Class> Classes { get; set; }
}
public class Class
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Student> Students { get; set; }
}
This created the three tables in the DB: Students, Classes and StudentsClasses (with StudentId and ClassId).
Now i've scaffolded the web api controllers and it created StudentController and ClassController. I now can make CRUD to the Student and Class entity separately but how can i make CRUD to the relationship table (StudentsClasses) ? Another controller for that table ? Or multiple POST parameters ?
My real problem is that I want in my client to POST a Class, then POST a Student and finally POST a Student to a Class (should be in relation table StudentsClasses).
Upvotes: 1
Views: 1966
Reputation: 5762
As I can understand from your question, you will have both Student
and Class
created in your database (Perhaps each one has a page with it's CRUD operations). Then, you'll have another page that will be responsible to add classes to an existing student.
If this is what you want, you'll just need to update an existing user and populate the Classes
property of the Student
entity.
E.g: You want to insert classes Math 1
and Chemistry 1
to student John
:
using (var dbContext = new SchoolContext())
{
//Get the existing student "John by its id"
var student = context.Student.FirstOrDefault(x => x.Id == id);
//fetch the classes from database (by id)
var math = context.Class.FirstOrDefault(x => x.Id == mathId);
var chemistry = context.Class.FirstOrDefault(x => x.Id == chemId);
student.Classes.Add(math);
student.Classes.Add(chemistry);
context.Entry(student).State = EntityState.Modified;
context.SaveChanges();
}
1 - Just be aware that you'll need to handle cases where an existing student already has classes. In this scenario, you can either delete all existing classes and only care for the ones, or create some kind of validation to take care of that.
2 - If you end up not fetching either student nor classes from the database, they will be created. So if you do this:
using (var dbContext = new SchoolContext())
{
var student = new Student { Name = "John"};
var math = new Class { Name = "Math 1"};
var chemistry = new Class { Name = "Chemistry 1"};
student.Classes.Add(math);
student.Classes.Add(chemistry);
context.Student.Add(student);
context.SaveChanges();
}
Entity Framework will create a record in Student
, 2 records in Class
and two records in the relationship table StudentClass
Upvotes: 0