![](/img/trans.png)
[英]EF Core 3.1 Removing parent entity with child relations + save changes + reuse same child id in new parent = concurrent exception
[英]Removing child entity from parent entity - EF Core 2.2
我想從一個實體中存在的集合中刪除一個項目。 我面臨的問題是:
-實體已從上下文中刪除
-保存更改后,實體仍然存在
父對象:
public class MyObject
{
public int Id { get; private set; }
public ICollection<ChildObject> ChildObjcets { get; private set; }
public void RemoveChildObject(ChildObject @object)
{
this.ChildObjcets.Remove(@object);
}
}
子對象:
public class ChildObject
{
public int Id { get; private set; }
public MyObject MyObject { get; set; }
public int MyObjectId { get; set; }
}
我試過的
public void Proceed()
{
//myObject contain 4 child objects inside
var myObject = _repo.GetMyObject();
var childObject = _repo.GetChildObject();
myObject.RemoveChildObject(childObject);
//myObject contain 3 items now
}
在保存更改之前,我在更改跟蹤器中看不到已刪除的實體-應該刪除狀態嗎?
var childObjects = ChangeTracker.Entries().Where(x => x.Entity is ChildObject).ToList(); // returns 3 - the removed one does not exist
但是,當我保存更改時,根對象仍然包含4個實體-因此子對象根本沒有被刪除
_repo.SaveChanges();
var myObject = _repo.GetMyObject();
任何想法如何處理從根實體刪除子對象?
在Entity Framework 6中,執行此操作的更快方法是
context.Children.RemoveRange(parent.Children)
卸下ChildObject
從ChildObjcets
(另外,還要注意錯別字)收集方法去除的關系,而不是去除實體DbContext
。 要完全刪除實體,您需要在DbSet<ChildObject>
上顯式調用Remove
,您不能直接從根對象執行此操作。
我建議將其實際引用的位置移至_repo
。 它應該可以訪問DbContext
因此可以訪問任何DbSet<>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.