我有一個過程,我從數據庫中讀取上千條記錄下查詢EF背景下,每一個編碼成一個單獨的XML消息,併發送所述消息開了一個WCF服務。不能TPL
數據庫通過EF4模型引用。我正在使用TPL來並行化XML消息的創建。
var practice = (from patient in db.T_AccountHolder
join practitioner in db.T_Practitioner on patient.DefaultPractitioner_ID equals practitioner.Practitioner_ID
join _practice in db.T_Practice on practitioner.Practice_ID equals _practice.Practice_ID
where patient.AccountHolder_ID == accountholder_id
select _practice).FirstOrDefault();
我得到以下異常:
ArgumentException: An item with the same key has already been added.
經過大量的研究,我發現,EF不分配一個新的關鍵,同樣查詢結果與第一個LINQ查詢時出現問題,這意味着如果您查詢具有相同結果的同一個表,則會發生上述異常(因爲結果在同一個數據上下文中)。
由於我使用TPL,我在那確切情況。我唯一的辦法是不使用EF嗎?回到正常的ADO.NET查詢?
我搜索上下這個優秀的網站和谷歌,但似乎無法找到一個類似類型的問題。
編輯:這是一個錯誤的堆棧跟蹤。
Exception message: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Data.Objects.ObjectStateManager.AddStateManagerTypeMetadata(EntitySet entitySet, ObjectTypeMapping mapping)
at System.Data.Objects.ObjectStateManager.GetOrAddStateManagerTypeMetadata(Type entityType, EntitySet entitySet)
at System.Data.Objects.ObjectStateManager.AddEntry(IEntityWrapper wrappedObject, EntityKey passedKey, EntitySet entitySet, String argumentName, Boolean isAdded)
at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
at lambda_method(Closure , Shaper)
at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
at System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1[TResult](IEnumerable`1 sequence)
at System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
at System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)
at WCFServiceTest.Messages.CreateAccountHolderMessage(Int32 accountholder_id) in C:\Users\Chris\documents\visual studio 2010\Projects\WCFServiceTest\WCFServiceTest\Messages.cs:line 116
at WCFServiceTest.Messages.CreateParallelMessagesForAccountHolder(Int32 accountholder_id, manmayEntities _db, List`1 queue) in C:\Users\Chris\documents\visual studio 2010\Projects\WCFServiceTest\WCFServiceTest\Messages.cs:line 2482
at WCFServiceTest.ParallelWork.<>c__DisplayClass22.<ProcessData_EF>b__1f(Int32 patient_id) in C:\Users\Chris\documents\visual studio 2010\Projects\WCFServiceTest\WCFServiceTest\ParallelWork.cs:line 298
指定每個線程的新上下文不是回答。今天早上試過並得到了類似的結果(「實體已經存在」類型的錯誤)。 – Chris 2010-12-21 06:33:40