问题
Hi I have read alot but couldn't really figure out how this is suppose to work out. Following this tutorial, I couldn't quite figure out how to input data into 2 models at once with a Foreign Key mapping done properly.
Supposedly I have to 2 models (following the tutorial), for example student and enrollment and I want to input data to both tables at the same time, looking at other stack overflow posts, I found out that are 2 ways to incorporate 2 views into the model, either by creating a "big view" or using partial view which I have done in this case. So by returning 2 objects to the controller and having it saved to the DB as shown below, it works, except that Enrollment doesn't have any link with Student via studentID (Foreign Key). Is there a way to set it or bind it together?
Currently I can save both individual set of data to the DB. I just cannot seem to figure out how to set the foreign key.
What I have now in 2 DBs is
Student | Enrollment
ID LastName ID <Some Column> StudentID
1 XXX 1 XXX NULL (Need this to be 1)
How do I get StudentID to be 1?
public async Task<IActionResult> Create([Bind("ID,LastName")] Student student, [Bind("<Some data inside enrollment>")] Enrollment enrollment)
{
if (ModelState.IsValid)
{
_context.Add(student);
await _context.SaveChangesAsync();
_context.Add(enrollment);
await _context.SaveChangesAsync();
return View(student);
}
Thank you very much! Your help is much appreciated! :)
回答1:
This would help,
var resultStudent = _context.Add(student);
enrollment.student_id = resultStudent.id;
_context.Add(enrollment);
await _context.SaveChangesAsync();
or
enrollment.Student = student;
_context.Enrollments.Add(enrollment);
await _context.SaveChangesAsync();
回答2:
Modified Simonare answer a bit and this worked for me. Seems like var resultStudent isn't required, but the general idea of setting the ID inside the controller is there.
_context.Add(student);
enrollment.studentID = student.ID;
_context.Add(enrollment);
await _context.SaveChangesAsync();
来源:https://stackoverflow.com/questions/53948414/net-core-ef-core-2-models-in-1-view-create-operation