使用Entity Framework Code First(4.1)
调用System.Data.Entity.DbContext.GetValidationErrors()时出现以下异常"An item with the same key has already been added."
堆栈跟踪如下:
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Data.Metadata.Edm.ObjectItemConventionAssemblyLoader.TryCreateType(Type type, StructuralType cspaceType, EdmType& newOSpaceType)
at System.Data.Metadata.Edm.ObjectItemConventionAssemblyLoader.LoadTypesFromAssembly()
at System.Data.Metadata.Edm.ObjectItemAssemblyLoader.Load()
at System.Data.Metadata.Edm.ObjectItemAssemblyLoader.LoadAssemblies(IEnumerable`1 assemblies, ObjectItemLoadingSessionData sessionData)
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData)
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, KnownAssembliesSet knownAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage, Object& loaderCookie, Dictionary`2& typesInLoading, List`1& errors)
at System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(ObjectItemCollection objectItemCollection, Assembly assembly, Boolean loadReferencedAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage)
at System.Data.Metadata.Edm.ObjectItemCollection.ExplicitLoadFromAssembly(Assembly assembly, EdmItemCollection edmItemCollection, Action`1 logLoadMessage)
at System.Data.Metadata.Edm.MetadataWorkspace.ExplicitLoadFromAssembly(Assembly assembly, ObjectItemCollection collection, Action`1 logLoadMessage)
at System.Data.Entity.Infrastructure.DbCompiledModel.CreateObjectContext[TContext](DbConnection existingConnection)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.LazyInternalContext.get_ObjectContext()
at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force)
at System.Data.Entity.Internal.InternalContext.GetStateEntries(Func`2 predicate)
at System.Data.Entity.DbContext.GetValidationErrors()
不幸的是,我无法确定问题的来源,也不知道poco实体导致了这个问题。
有人有线索吗?
由于
答案 0 :(得分:1)
是的,这是一个有趣的问题,这里的问题来自于尝试重新附加已附加到上下文的实体。这可能来自逻辑错误,或者您可能在不清除附加对象的情况下重用上下文。数据库上有一个本地集合,您可以使用它来查看当前附加到上下文的项目。
ctx.YourEntityCollection.Local