I'm really new to ASP.NET Core so I apologize if this is a silly question, but I've spent so many hours trying to figure this out.
I have 2 models, Teacher
and Student
. The relationship is one teacher to many students. This is a backend API project and Im working on a PUT method which can update fields in both models simultaneously in one request.
Here's my Teacher
class:
public partial class Teacher
{
public Teacher()
{
Students = new HashSet<Student>();
}
public int TeacherId { get; set; }
public string Name { get; set; }
... tons of other properties ...
}
Here's my Student
class:
public partial class Student
{
public int Id { get; set; }
public int TeacherId { get; set; }
public string Name { get; set; }
public virtual Teacher Teacher { get; set; }
}
Here's the controller:
[HttpPut("{id}")]
public async Task<IActionResult> PutTeachers(int id, TeacherViewModel model)
{
var result = await _service.UpdateAsync(model);
return Ok(result.Message);
}
(The code above is simplified) - It takes in a TeacherViewModel
which restricts the number of fields to be returned - I used another class as a service to do the update
Here's the service class:
public class TeacherService
{
private readonly Repository<Teacher> _repository;
public TeacherService(DatabaseContextWrapper context)
{
_repository = new Repository<Teacher>(context);
}
public async Task<ITransactionResult> UpdateAsync(TeacherViewModel model)
{
var teacher = _repository.FindAsync(model.TeacherId).Result;
teacher.TeacherId = model.TeacherId;
teacher.Name = model.Name;
teacher.Students.Clear();
foreach(var student in model.Students)
{
teacher.Students
.Add(new Student
{
Id = Student.Id,
TeacherId = Student.TeacherId
Name = Student.Name
});```
}
}
}
My reasoning is to add the Student
model to the to students under the Teacher
model but it doesn't iterate through. If I comment out the clear code, the update will work but it won't cross update. It just simply wont iterate through. I guess I'm pretty lost at this point. Any help would be appreciated!
Edit 1 (Entity relationship configuration)
modelBuilder.Entity<Student>(entity => {
entity.HasOne(d => d.Teacher)
.WithMany(p => p.Students)
.HasForeignKey(d => d.TeacherId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Students_Teachers");
});
This is my configuration
Try adding the reverse config to your parents entity:
modelBuilder.Entity<Teacher>(entity =>
{
entity.HasMany(d => d.Students)
.WithOne(p => p.Teacher)
.HasForeignKey(d => d.TeacherId);
});
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.