簡體   English   中英

ObjectStateManager中已存在具有相同鍵的對象

[英]An object with the same key already exists in the ObjectStateManager

這個錯誤已被問及很多。 但我認為沒有一個案例適用於我的特定情況,或者至少不完全適用。

我正在創建具有2個導航屬性的新實體,這些屬性是集合。 實體和導航屬性都是數據庫中不存在的新實體。 我的問題是,每當我嘗試將實體附加到上下文時,如果任何一個集合具有多個元素,我都會遇到上述異常。

我在以下代碼的Attach()指令中收到此錯誤:

using (var context = new NSModel())
{
    context.Notifications.Attach(e);
    context.ObjectStateManager.ChangeObjectState(e,
    StateHelpers.GetEquivalentEntityState(e.State));

    foreach (NavigationProperty1 np in e.NavigationProperty1s)
        context.ObjectStateManager.ChangeObjectState(np,
        StateHelpers.GetEquivalentEntityState(np.State));

    foreach (NavigationProperty2 np in e.NavigationProperty2s)
        context.ObjectStateManager.ChangeObjectState(np,
        StateHelpers.GetEquivalentEntityState(np.State));

    context.SaveChanges();
    return e;
}   

代碼用於網站,因此實體是無狀態的,並且每次調用都會創建和處理上下文...

有任何想法嗎?

實體和導航屬性都是數據庫中不存在的新實體。

然后問題是:你為什么使用Attach 通過使用Attach告訴EF的entites的在數據庫中,EF會考慮的首要關鍵屬性,如數據庫中的PK列值的值。 因為這些屬性必須是唯一的,一旦你有兩個具有相同鍵值的entite,EF就會抱怨。 當您將身份自動生成為關鍵屬性並且在創建實體時不設置值時,很可能出現這種情況。

簡單的例子:

public class Parent
{
    public Parent
    {
        Children = new List<Child>();
    }

    public int Id { get; set; }
    public ICollection<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }
}

這段代碼......

using (var ctx = new MyContext())
{
    var parent = new Parent();
    var child1 = new Child();   // <- Id is 0
    var child2 = new Child();   // <- Id is 0 as well

    parent.Children.Add(child1);
    parent.Children.Add(child2);

    ctx.Parents.Attach(parent);  // <- exception here

    //...
}

...將拋出異常,因為EF嘗試使用相同的鍵0附加兩個不同的子實例。 當第二個子child2將被附加時,它說:“ObjectStateManager中已存在具有相同鍵(即0 )的對象(即child1 )”。

如果要將整個對象圖作為新實體添加到數據庫中,則只需調用context.Notifications.AddObject(e); 而不是Attach

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM