【问题标题】:Entity Framework Core Update Duplicating实体框架核心更新复制
【发布时间】:2018-06-29 18:50:06
【问题描述】:

当尝试使用子实体集合更新实体时,子集合的每个成员都是重复的。为什么在控制器中使用 Update 方法时子实体会重复?

此应用程序使用 ASP.NET Core 2.1 和 Entity Framework Core,连接到 Visual Studio 2017 中的 MS SQL Server LocalDB。

ParentEntity.cs

namespace MyProject.Models
{

    public enum EntityType { Type1, Type2, Type3}

    public class ParentEntity
    {
        public int ParentEntityID { get; set; }

        public string Text { get; set; }

        public EntityType EntityType { get; set; }

        public ICollection<ChildEntity> ChildEntities { get; set; }

    }
}

ChildEntity.cs

namespace MyProject.Models
{
    public class ChildEntity
    {
        public int ChildEntityID { get; set; }
        public string ChildEntityText { get; set; }

        public int ParentEntityId { get; set; }
        public ParentEntity ParentEntity { get; set; }
    }
}

EditEntity.cshtml

@model ParentEntity

<h1>Edit Entity</h1>
<form asp-controller="Entity" asp-action="Edit" method="post">
    <input type="hidden" asp-for="ParentEntityID" />
    <input type="hidden" asp-for="EntityType" />
    <label asp-for="Text"></label>
    <input asp-for="Text" class="form-control" />

    @{ int i = 1; var a = Model.ChildEntities.ToArray(); }
    @for(var c = 0; c < Model.ChildEntities.Count(); c++)
    {
        <label>Child Entity @i</label>
        <input name="ChildEntities[@c].ChildEntityText" value="@a[c].ChildEntityText" />
        i++;
    }

    <button type="submit">Save</button>
</form>

EntityController.cs

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ParentEntityID, Text, EntityType, ChildEntities")] ParentEntity pa)
{
    if (id != pa.ParentEntityId)
    {
        return NotFound();
    }

    if (ModelState.IsValid)
    {
        try
        {
            context.Update(pa);
            await context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {

        }
        return RedirectToAction("EditEntity");
    }
    return View(pa);
}

【问题讨论】:

  • 首先,自己的解决方案不应该放在问题中,而是作为一个自我回答。其次,您解决问题的方式清楚地表明它不是 EF Core 问题,并且@Ryan Bennett 的答案是正确的,因此应该被接受。

标签: c# asp.net-core entity-framework-core


【解决方案1】:

我要检查的第一件事是 ChildEntities 上的 ChildEntityIds 是否在从控制器进入时实际设置。如果 id 为 0,EF 会认为它们是新实体并进行插入。

如果它们确实将 id 设置为非零整数,我会尝试对它们进行循环并附加实体,以便上下文了解它们。比如:

foreach(var child in pa.children){
    context.Attach(child);
}

await context.SaveChanges();

【讨论】:

    【解决方案2】:

    所需要的只是在视图中的 for 循环的每一行中添加以下内容。

    <input type="hidden" name="ChildEntities[@c].ChildEntityID" value="@a[c].ChildEntityText" class="form-control" />
    

    【讨论】:

      猜你喜欢
      • 2018-05-19
      • 2020-07-19
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      相关资源
      最近更新 更多