更新包含实体框架中的对象列表的对象的最佳方法

ami*_*iko 2 .net c# entity-framework asp.net-web-api

我的 API 中有以下模型:

namespace API.Models
{
public class StudentDetailsViewModel
{
    [Key]
    public int StudentId { get; set; }
    public AddressViewModel Address  { get; set; }
    public List<CoursesViewModel> Courses { get; set; }
}

public class AddressViewModel
{
    public int AddressId { get; set; }
    public int StudentId { get; set; }
    public string Address { set; set; }
}

public CoursesViewModel
{
    public int CourseId { get; set; }
    public int StudentId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Grade { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)

我正在为 StudentDetailsViewModel 编写 PUT 方法。此模型中的列表可以删除或添加多个记录,或者更新其中一条记录中的多个字段。例如,更新的一门课程的成绩或添加或删除的课程。

更新包含上述对象列表的模型的最佳方法是什么?最好删除整个列表并重新添加它们吗?

到目前为止我有以下内容:

[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutStudenDetailsViewModel(StudentDetailsViewModel studentDetailsViewModel)
{
    if(!ModelState.IsValid)
        return BadRequest(ModelState);

    var address = new DataAccess.Address
    {
        AddressID = studentDetailsViewModel.Address.AddessId,
        StudentID = studentDetailsViewModel.Address.StudentId,
        Address = studentDetailsViewModel.Address.Address   
    };

    _context.Entry(address).State = EntityState.Modified;

    // TODO: This is where the list Course entity needs to be updated

    try
    {
        await _context.SaveChangesAsync();
    }
    catch(DbUpdateConcurrencyException)
    {
        if(!AddressViewModelExists(address.AddressID))
            return NotFound();

        throw;
    }

    return StatusCode(HttpStatusCode.NoContent);
}
Run Code Online (Sandbox Code Playgroud)

Rus*_*rov 5

只是EF Core 的 MS 文档中的一个示例

public static void InsertOrUpdateGraph(BloggingContext context, Blog blog)
{
    var existingBlog = context.Blogs
        .Include(b => b.Posts)
        .FirstOrDefault(b => b.BlogId == blog.BlogId);

    if (existingBlog == null)
    {
        context.Add(blog); //or 404 response, or custom exception, etc...
    }
    else
    {
        context.Entry(existingBlog).CurrentValues.SetValues(blog);
        foreach (var post in blog.Posts)
        {
            var existingPost = existingBlog.Posts
                .FirstOrDefault(p => p.PostId == post.PostId);

            if (existingPost == null)
            {
                existingBlog.Posts.Add(post);
            }
            else
            {
                context.Entry(existingPost).CurrentValues.SetValues(post);
            }
        }
    }

    context.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)