在Entity Framework中更新包含对象列表的对象的最佳方法

时间:2018-11-08 16:33:35

标签: c# .net 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; }
}
}

我正在为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);
}

1 个答案:

答案 0 :(得分:1)

仅以MS documentation for EF Core

为例
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();
}