【发布时间】: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