2017-03-18 12 views
-1

エラー:は失敗しました

Additional information: Attaching an entity of type 'Entities.Customer' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not received database-generated key values. In this case use the 'Add' method or the 'Added' entity to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

マイコード:

public bool Update(TEntity entity) 
{ 
     bool result = false; 

     try 
     { 
      EntitySet.Attach(entity); 

      Context.Entry<TEntity>(entity).State = EntityState.Modified; 
      Context.SaveChanges(); 
      result = true; 
     } 
     catch (Exception) 
     { 
      throw; 
     } 

     return result; 
} 

私が働いていた。この方法で、私は知らないので、それはもはや作品

+0

...役立ちます。 'EntitySet'がどこで初期化されたのか、それが生涯であるのかは不明です。このエラーは通常、コンテキストの存続期間が長すぎることを示します。 –

+0

本当に答えが必要な場合は、コメントと回答に有意義なフィードバックを与えるためにもっと努力する必要があります。 –

答えて

0

dbまたはローカルコンテキストからエンティティを取得し、それを更新してみてください。たとえば、キャッチブロックでそれを行います。その場合のcatchブロックの 例:

catch 
{ 
    // get entity here 
    // for example Context.Set<TEntity().Local.FirstOrDefault(selector); 
    //or .Find() instead of .FirstOrDefault() 
    Context.Entry(entity).State = EntityState.Modified; 
    Context.SaveChanges(); 
} 
+0

が動作しません。それは私が持っている – luistejadaa

0

は、ブロックを使用して、このアプローチを試してみてください:

try 
{ 
    /* For avoiding "Attaching an entity of type 'Xxxxx' failed because another entity of 
    the same type already has the same primary key value." error use this method like this */ 
    using (var context = new Context.Entry<TEntity>()) 
    { 
     context.Entry(entity).State = EntityState.Modified; // modified 
     context.SaveChanges(); //Must be in using block 
     result = true; 
    } 
} 

・ホープこれはあなたがあなたのコードの小さな断片を示し

+0

どちらも:(動作しない – luistejadaa

関連する問題