【问题标题】:MVC5 ICollection<T> remove entity using RemoveAt c# EF 6.1MVC5 ICollection<T> 使用 RemoveAt c# EF 6.1 删除实体
【发布时间】:2018-11-20 00:36:27
【问题描述】:

我正在将我的 MVC 3 应用程序/Linq-To-Sql 升级到 MVC 5 Entity Framework 6.1。我有一个项目列表(ID、名称等)。要更改列表,用户可以通过添加或删除表格行来添加或删除项目。使用表单集合我检查新项目并删除旧列表中存在的项目。使用以下内容:

//.....
List<int> idsToKeep = new List<int>();
for (int i = 0; i < visit.Students.Count; i++)
{
  Students om = visit.Students.ElementAt(i);
  if (om.StudentsId == 0)
    continue;
  bool itemExists = false;
  int itemToDelete = 0;
  foreach (int id in idsToKeep)
    if (om.StudentsId == id)
    {
      itemExists = true;
    }
    else
    {
      itemToDelete = id;
    }

  if (!itemExists)
  {
    var entitySet = visit.Students.Where(x => x.StudentsId == 0 || idsToKeep.Contains(x.StudentsId)).ToList();
    entitySet.RemoveAt(i);
    //      _studentRepository.RemoveStudentsType(itemToDelete); 
    //    visit.Students.RemoveAt(i);
    i--;
  }
}  

在 Linq-to-Sql 中,我使用了:

visit.Students.RemoveAt(i);

无法解析 RemoveAt,因为列表是 ICollection。所以我用了:

var entitySet = visit.Students.Where(x => x.StudentsId == 0 || idsToKeep.Contains(x.StudentsId)).ToList();
entitySet.RemoveAt(i);

程序一直在循环,但没有任何反应!非常感谢您的建议

【问题讨论】:

  • 你忘了在 DbContext 对象上调用 SaveChanges 方法

标签: c# asp.net-mvc linq entity-framework


【解决方案1】:

您正在从 Entity Framework 跟踪的集合的副本中删除一个实体。果然,您的上下文不会注意到该更改,因为它完全不知道副本:它只注册原始 ICollection&lt;T&gt;(即visit.Students)中的更改。

您应该首先考虑在正确的索引处找到具体实体 - 可能通过使用 LINQ 的“ElementAt”,如下所示:

var entityAtIndex = visit.Students.ElementAt(i);

visit.Students.Remove(entityAtIndex);

或者,更好的是,只需使用visit.Students.Remove(om),因为它会指向您首先要删除的确切实例。

【讨论】:

  • 必须添加 studentRepository.Delete(om);谢谢
猜你喜欢
  • 1970-01-01
  • 2021-02-19
  • 2011-12-01
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
  • 2011-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多