在这里我们有一个图书与其章节的一对多关系。我们需要知道如何更新这个关系中的嵌套项。假设我们要更新某本书的某个章节的内容。
模型:
public class Book
{
public int BookId { get; set; }
public string BookTitle { get; set; }
public ICollection Chapters { get; set; }
}
public class Chapter
{
public int ChapterId { get; set; }
public string ChapterTitle { get; set; }
public string ChapterContent { get; set; }
public int BookId { get; set; }
public Book Book { get; set; }
}
控制器方法:
[HttpPut("{bookId}/chapters/{chapterId}")]
public async Task UpdateChapter(int bookId, int chapterId, [FromBody] Chapter chapter)
{
if (bookId != chapter.BookId || chapterId != chapter.ChapterId)
{
return BadRequest("Request Ids does not match with the body.");
}
var existingChapter = await _context.Chapters
.Include(b => b.Book)
.SingleOrDefaultAsync(c => c.BookId == bookId && c.ChapterId == chapterId);
if (existingChapter == null)
{
return NotFound();
}
existingChapter.ChapterTitle = chapter.ChapterTitle;
existingChapter.ChapterContent = chapter.ChapterContent;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ChapterExists(bookId, chapterId))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
在这个方法中,我们首先检查提交的章节的ID是否与请求的ID匹配。然后,我们在数据库中查找现有章节,更新了章节内容后存储更改。如果出现并发异常,则检查章节是否存在。如果章节不存在