简体   繁体   English

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

[英]Best way to update an object containing a list of objects in Entity Framework

I have the following models in my 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; }
}
}

I am writing a PUT method for StudentDetailsViewModel. 我正在为StudentDetailsViewModel编写PUT方法。 The list in this model could have a number of records removed or added or a number of fields in one of the records updated. 此模型中的列表可以删除或添加许多记录,或者更新其中一个记录中的许多字段。 For example, grade for one of the courses updated or a course added or dropped. 例如,更新其中一门课程的成绩,或添加或删除一门课程。

What is the best approach in updating a model containing an object list like the above? 更新包含上述对象列表的模型的最佳方法是什么? Is it best to delete the entire list and re-add them? 最好删除整个列表并重新添加它们吗?

I have the following thus far: 到目前为止,我有以下几点:

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

Just an example from MS documentation for EF Core 仅是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();
}

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

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