gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:58:21 26 4
gpt4 key购买 nike

我的 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 方法。此模型中的列表可以删除或添加多个记录,或者更新其中一条记录中的多个字段。例如,更新的一门类(class)或添加或删除的类(class)的成绩。

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

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

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

最佳答案

只是 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();
}

关于c# - 更新包含 Entity Framework 中的对象列表的对象的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53212118/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com