【发布时间】:2019-04-03 15:26:20
【问题描述】:
我是 EF 核心的新手,并按照本教程 getting started with EF 创建了一个测试项目
这是一个包含一些帖子的博客。
我已更新 Edit GET 方法以包含帖子
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var blog = await _context.Blog.Include(x => x.Post).SingleOrDefaultAsync(x => x.BlogId == id);
if (blog == null)
{
return NotFound();
}
return View(blog);
}
我已更新模型以便能够为帖子编制索引。
public partial class Blog
{
public Blog()
{
Post = new List<Post>();
}
public int BlogId { get; set; }
public string Url { get; set; }
public virtual IList<Post> Post { get; set; }
}
在我的 Edit.cshtml 中,我添加了这个部分来显示帖子:
@for (int i = 0; i < Model.Post.Count; i++)
{
<div class="form-group">
<label asp-for="Post[i].Title" class="control-label"></label>
<input asp-for="Post[i].Content" class="form-control" />
</div>
}
但是,当我尝试更新更新的 Post 对象时,它只是被添加到集合中,而不是更新现有的。这意味着我的帖子每次更新都会翻倍。
这是我的编辑 POST 方法。我检查了 blog 的值是否包含帖子集合中的正确值。
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("BlogId,Url,Post")] Blog blog)
{
if (id != blog.BlogId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(blog);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!BlogExists(blog.BlogId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(blog);
}
我做错了什么?
【问题讨论】:
标签: entity-framework model-view-controller asp.net-core