简体   繁体   English

ASP.NET Core 中的跨模型更新

[英]Cross model update in ASP.NET Core

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.我对 ASP.NET Core 真的很陌生,所以如果这是一个愚蠢的问题,我深表歉意,但我花了很多时间试图解决这个问题。

I have 2 models, Teacher and Student .我有 2 个模型, TeacherStudent 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.这是一个后端 API 项目,我正在研究一种 PUT 方法,该方法可以在一个请求中同时更新两个模型中的字段。

Here's my Teacher class:这是我的Teacher课:

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:这是我的Student类:

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 (上面的代码是简化的) - 它采用了一个TeacherViewModel ,它限制了要返回的字段数 - 我使用另一个类作为服务来进行更新

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.我的推理是将Student模型添加到Teacher模型下的学生,但它不会迭代。 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)编辑 1(实体关系配置)

 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);
            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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