【问题标题】:EF Core 2.1 how to update data in related tableEF Core 2.1 如何更新相关表中的数据
【发布时间】: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


    【解决方案1】:

    PostId 似乎没有隐藏输入字段,因此在您的 POST 操作中属于博客一部分的帖子被视为新记录并插入。

    <div class="form-group">
            <input type="hidden" asp-for="Post[i].PostId" />
            <label asp-for="Post[i].Title" class="control-label"></label>
            <input asp-for="Post[i].Content" class="form-control" />                    
    </div>
    

    【讨论】:

    • 很好,它有效。这不是很明显,至少对我来说不是。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-03-29
    • 2020-09-04
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 2017-01-29
    相关资源
    最近更新 更多