实体框架6运行时错误:“给定键不存在于字典” [英] Entity Framework 6 Runtime Error: "given key was not present in the dictionary"

查看:435
本文介绍了实体框架6运行时错误:“给定键不存在于字典”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个使用EF6代码优先和每层次表的ASP.Net应用程序



当我尝试用dbcontext做任何有意义的事情时,我收到这个错误例如查询,更新等):

  {
消息:发生错误。 ,
ExceptionMessage:准备命令定义时发生错误。有关详细信息,请参阅内部异常,
ExceptionType:System.Data.Entity.Core.EntityCommandCompilationException,
StackTrace:在System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory,DbCommandTree commandTree,DbInterceptionContext interceptionContext,IDbDependencyResolver resolver,BridgeDataReaderFactory bridgeDataReaderFactory,ColumnMapFactory columnMapFactory)\r\\\
在System.Data.Entity.Core.EntityClient.Internal.EntityProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest,DbCommandTree commandTree,DbIn terceptionContext interceptionContext)\r\\\
在System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.CreateCommandDefinition(ObjectContext context,DbQueryCommandTree tree)\r\\\
在System.Data.Entity.Core.Objects.Internal .ObjectQueryExecutionPlanFactory.Prepare(ObjectContext context,DbQueryCommandTree tree,Type elementType,MergeOption mergeOption,Boolean streaming,Span span,IEnumerable`1 compiledQueryParameters,AliasGenerator aliasGenerator)\r\\\
在System.Data.Entity.Core.Objects.ELinq中。 ELIQQueryState.GetExecutionPlan(Nullable`1 forMergeOption)\r\\\
在System.Data.Entity.Core.Objects.ObjectQuery`1。<> c__DisplayClass7。< GetResults> b__6()\r\\\
在System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction [T](Func`1 func,IDbExecutionStrategy executionStrategy,Boolean startLocalTransaction,Boolean releaseConnectionOnSuccess)\r\\\
在System.Data.Entity.Core.Objects.ObjectQuery` 1.<&克(System.Data.Entity)中的.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\\\
在System.Data.Entity.Core.Objects.ObjectQuery`1。< System.Collections.Generic.IEnumerable< T> ;. GetEnumerator> b__0()\r\\\
在System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()\r\\\
在System.Collections.Generic.List`1..ctor(IEnumerable`1集合)\r\\\
在System.Linq.Enumerable.ToList [TSource](IEnumerable`1源)\rn在SealingServer.Controllers.PdfsController。< PostPdf> d__4.MoveNext()在C: \Users\thoma_000\Documents\All Code\SealServer\SealingServer\Controllers\PdfsController.cs:line 93\r\\\
---从前一个位置抛出异常的堆栈跟踪结束--- \r\\\
在System.Runtime.Compile rServices.TaskAwaiter.ThrowForNonSuccess(任务任务)\rn在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)\r\\\
在System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\\ \\
在System.Threading.Tasks.TaskHelpersExtensions中。< CastToObject> d__3`1.MoveNext()\\在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)上的r\\\
在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)\r\\\
在System.Runtime.CompilerServices .TaskAwaiter`1.GetResult()\r\\\
在System.Web.Http.Controllers.ApiControllerActionInvoker。< InvokeActionAsyncCore> d__0.MoveNext()\r\\\
---从上一个位置结束堆栈跟踪其中抛出异常--- \r\\\
在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSucces s(任务任务)\\\\
在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)\r\\\
在System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\ n在System.Web.Http.Controllers.ActionFilterResult。< ExecuteAsync> d__2.MoveNext()\r\\\
---结束堆栈跟踪从之前的位置异常被抛出--- \r\\\
(System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess .GetResult()\\\\
在System.Web.Http.Dispatcher.HttpControllerDispatcher。< SendAsync> d__1.MoveNext(),
InnerException:{
Message:发生错误,
ExceptionMessage:给定的键不在字典中。,
ExceptionType:System.Collections.Generic.KeyNotFoundEx ception,
StackTrace:在System.Collections.Generic.Dictionary`2.get_Item(TKey键)\r\\\
在System.Data.Entity.Core.Mapping.ViewGeneration.Structures.MemberDomainMap .GetDomainInternal(MemberPath path)\r\\\
在System.Data.Entity.Core.Mapping.ViewGeneration.QueryRewriting.FragmentQueryKB.CreateIsOfTypeCondition(MemberPath currentPath,IEnumerable`1 derivedTypes,MemberDomainMap domainMap)\r\\\
在系统.Data.Entity.Core.Mapping.ViewGeneration.QueryRewriting.FragmentQueryKB.CreateVariableConstraintsRecursion(EdmType edmType,MemberPath currentPath,MemberDomainMap domainMap,EdmItemCollection edmItemCollection)\r\\\
在System.Data.Entity.Core.Mapping.ViewGeneration.QueryRewriting。 FragmentQueryKB.CreateVariableConstraintsRecursion(EdmType edmType,MemberPath currentPath,MemberDomainMap domainMap,EdmItemCollection edmItemCollection)\r\\\
在System.Data.Entity.Core.Mapping.ViewGeneration.ViewgenContext..ctor(ViewTarget viewTar获取,EntitySetBase范围,IList`1 extentCells,CqlIdentifiers标识符,ConfigViewGenerator配置,MemberDomainMap queryDomainMap,MemberDomainMap updateDomainMap,EntityContainerMapping entityContainerMapping)\r\\\
在System.Data.Entity.Core.Mapping.ViewGeneration.ViewGenerator.CreateViewgenContext(EntitySetBase extent ,ViewTarget viewTarget,CqlIdentifiers标识符)\r\\\
在System.Data.Entity.Core.Mapping.ViewGeneration.ViewGenerator.GenerateDirectionalViewsForExtent(ViewTarget viewTarget,EntitySetBase extent,CqlIdentifiers identifier,KeyToListMap`2 views)\r\\\
在System.Data.Entity.Core.Mapping.ViewGeneration.ViewGenerator.GenerateDirectionalViews(ViewTarget viewTarget,CqlIdentifiers标识符,KeyToListMap`2视图)\r\\\
在System.Data.Entity.Core.Mapping.ViewGeneration.ViewGenerator.GenerateAllBidirectionalViews (KeyToListMap`2视图,CqlIdentifiers标识符)\r\\\
在System.Data.Entity.Core.Mapping.ViewGeneration.Vi ewgenGatekeeper.GenerateViewsFromCells(List`1 cells,ConfigViewGenerator config,CqlIdentifiers identifier,EntityContainerMapping containerMapping)\r\\\
在System.Data.Entity.Core.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGenerateViews(EntityContainerMapping entityContainerMap,Dictionary`2 resultDictionary)\\ \\ System.Data.Entity.Core.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGetGeneratedViews(EntityContainer容器)\\\\
在System.Data.Entity.Core.Common.Utils.Memoizer`2.Result中。在System.Data.Entity.Core.Common.Utils.Memoizer`2.Evaluate(TArg arg)\r\\\
在System.Data.Entity.Core.Mapping.StorageMappingItemCollection中GetValue()\r\\\
。 ViewDictionary.GetGeneratedView(EntitySetBase extent,MetadataWorkspace workspace,StorageMappingItemCollection storageMappingItemCollection)\r\\\
在System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.GetGeneratedView(EntitySetBase extent)\r \
在System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.ExpandView(ScanTableOp scanTableOp,IsOfOp&安培; typeFilter)\r\\\
在System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.ProcessScanTable(Node scanTableNode,ScanTableOp scanTableOp,IsOfOp& typeFilter)\r\\\
在System.Data.Entity.Core。 System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r\\\
在System.Data中的Query.PlanCompiler.PreProcessor.Visit(ScanTableOp op,Node n)\r\\\
.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op,Node n)\r\\\
在System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Visit(FilterOp op,Node n)\在System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n)上的System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r\\\
中的r \\ System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r\\\
在System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Vis \\\\在System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.VisitNavPropertyOp(PropertyOp op,Node n)\\ System.Data.Entity中的\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ Core.Query.PlanCompiler.PreProcessor.Visit(PropertyOp op,Node n)\r\\\
在System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r\\\
在系统.Data.Entity.Core.Query.PlanCompiler.PreProcessor.VisitScalarOpDefault(ScalarOp op,Node n)\r\\\
在System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r在System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(节点n)\\\\
在System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\\ \\ System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n)\r \在System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildre在System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op,Node n)上的n(节点n)\r\\\
在System.Data.Entity.Core.Query .PlanCompiler.PreProcessor.Visit(ProjectOp op,Node n)\r\\\
在System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r\\\
在System.Data。 Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op,Node n)\r\\\
在System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Visit(ProjectOp op,Node n)\r在System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r\\\
在System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n)\\ \\\\
在System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Process(Dictionary`2& tvfResultKeys)\r\\\
在System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Process(PlanCompiler planCompilerState,StructuredTypeInfo& typeInfo,Dictionary`2& tvfResultKeys)\r\\\
在System.Data.Entity System.Data.Entity.Core.EntityClient.Internal中的.Core.Query.PlanCompiler.PlanCompiler.Compile(List`1& providerCommands,ColumnMap& resultColumnMap,Int32& columnCount,Set`1& entitySets)\r\\\
。 EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory,DbCommandTree commandTree,DbInterceptionContext interceptionContext,IDbDependencyResolver resolver,BridgeDataReaderFactory bridgeDataReaderFactory,ColumnMapFactory columnMapFactory)
}
}

编辑



我重新开始使用新的数据库,并获得相同的结果任何实体,这使我相信它与我的DbContext有关,它看起来像这样:

  public class Sealin gServerContext:DbContext 
{
public SealingServerContext():base(name = TFMContext)
{
this.Database.Log = Console.Write;
this.Configuration.LazyLoadingEnabled = false;
}
public DbSet< Organization>组织{get;组; }

public DbSet< User>用户{get;组; }

public DbSet< Role>角色{get;组; }

public DbSet< ReviewerRole> ReviewerRoles {get;组; }
public DbSet< AnnotationTemplate> AnnotationTemplates {get;组; }
public DbSet< PaperItem> PaperItems {get;组; }
public DbSet< PaperRaster> PaperRasters {get;组; }

public DbSet& EngineerRole> EngineerRoles {get;组; }
public DbSet< Seal>密封{get;组; }
public DbSet< Signature>签名{get;组; }


public DbSet< Job>工作{get;组; }
public DbSet< JobFile> JobFiles {get;组; }
public DbSet< Pdf> Pdfs {get;组; }
public DbSet< PdfPage> PdfPages {get;组;

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity< AnnotationTemplate>()
.HasKey(annotationTemplate => annotationTemplate.ID);

modelBuilder.Entity< JobFile>()
.HasKey(pdf => pdf.ID);
modelBuilder.Entity< Pdf>()
.HasKey(pdf => pdf.ID)
.HasMany(pdf => pdf.PdfPages)
.WithRequired()
.HasForeignKey(pdfPage => pdfPage.Pdf_ID)
.WillCascadeOnDelete(true);

modelBuilder.Entity< Job>()
.HasKey(job => job.ID);
modelBuilder.Entity< Job>()
.HasMany(job => job.Files)
.WithRequired()
.HasForeignKey(jobFile => jobFile.Job_ID) ;
modelBuilder.Entity< Job>()
.HasMany(job => job.Regions)
.WithRequired()
.HasForeignKey(region => region.Job_ID) ;

modelBuilder.Entity< Organization>()
.HasKey(organization => organization.ID)
.HasMany(org => org.Users)
.WithRequired()
.HasForeignKey(user => user.Organization_ID);

modelBuilder.Entity< PaperItem>()
.HasKey(paperItem => paperItem.ID);

modelBuilder.Entity< PaperRaster>()
.HasKey(paperRaster => paperRaster.ID);

modelBuilder.Entity< Models.Files.PdfPage>()
.HasKey(pdfPage => pdfPage.ID);

modelBuilder.Entity< Region>()
.HasKey(region => region.ID);

modelBuilder.Entity< Role>()
.HasKey(role => role.ID);

modelBuilder.Entity< EngineerRole>()
.HasKey(role => role.ID);
modelBuilder.Entity< EngineerRole>()
.HasMany(engineeringRole => engineerRole.Seals)
.WithRequired()
.HasForeignKey(seal => seal.EngineerRole_ID) ;
modelBuilder.Entity< EngineerRole>()
.HasMany(engineerRole => engineerRole.Signatures)
.WithRequired()
.HasForeignKey(signature => signature.EngineerRole_ID) ;

modelBuilder.Entity& EngineerAdminRole>()
.HasKey(role => role.ID);

modelBuilder.Entity< ReviewerAdminRole>()
.HasKey(role => role.ID);

modelBuilder.Entity< ReviewerRole>()
.HasKey(reviewerRole => reviewerRole.ID)
.HasMany(reviewerRole => reviewerRole.AnnotationTemplates)
.WithOptional()
.HasForeignKey(annotation => annotation.ReviewerRole_ID);

modelBuilder.Entity< Seal>()
.HasKey(seal => seal.ID);

modelBuilder.Entity< Signature>()
.HasKey(signature => signature.ID);

modelBuilder.Entity< User>()
.HasKey(user => user.ID);
modelBuilder.Entity< User>()
.HasMany(user => user.Roles)
.WithOptional()
.HasForeignKey(role => role.User_ID) ;
}
}

Edit2



我一直在评论事情,并进行数据库迁移,并将其缩小到这个继承层次结构:

  [KnownType(typeof(PaperRaster))] 
public class PaperItem
{
public int ID {get;组; }

public PointF PdfPosition {get;组; }

public string ItemType {get;组;

public virtual void Move(PointF coordinatesTranslation)
{
}

protected PaperItem(string paperItemType,PointF pdfPosition)
{
ItemType = paperItemType;
PdfPosition = pdfPosition;
}

public virtual PaperItem DeepCopy()
{
返回新的PaperItem(PaperItem,新的PointF());
}


公共虚拟字符串ToJson()
{
//将所有属性转换为Json
return;
}
}

及其子类:

  public class PaperRaster:PaperItem 
{
public string Source {get;组; }
public string CrossOrigin {get;组; }
public Matrix Matrix {get;组;

$ b public PaperRaster(string source,string crossOrigin,Matrix matrix,PointF pdfPosition)
:base(Raster,pdfPosition)
{
this.Source =资源;
this.CrossOrigin = crossOrigin;
this.Matrix = matrix;
}

public PaperRaster(string json):base(Raster,new PointF())
{
JArray array = JArray.Parse(json);

JToken type = array [0];
JToken属性= array [1];
JToken position = array [2] [pdfPosition];


if(type.ToString()!=Raster)
{
抛出新的异常(不是PaperRaster);
}

var matrix = properties [matrix];
this.Matrix = new Matrix(float.Parse(matrix [0] .ToString()),float.Parse(matrix [1] .ToString()),
float.Parse ] .ToString()),float.Parse(matrix [3] .ToString()),
float.Parse(matrix [4] .ToString()),float.Parse(matrix [5] .ToString )));

//自定义编码属性

//注释的左下角(这就是iTextSharp插入它)

var x = position [x ]的ToString();
var y = position [y]。ToString();

this.PdfPosition = new PointF()
{
X = float.Parse(x),
Y = float.Parse(y)
};
}

public override void Move(PointF coordinatesTranslation)
{
this.Matrix.Translate(coordinatesTranslation.X,coordinatesTranslation.Y);
}

public override PaperItem DeepCopy()
{
返回新的PaperRaster(this.Source,this.CrossOrigin,this.Matrix,this.PdfPosition);
}

public override string ToJson()
{
//将所有属性转换为Json
return;
}
}

如果我注释掉孩子类并做一个db移民。一切都恢复正常。这种继承层次结构导致EF错误地生成表



其他注释



奇怪的sidenote,这样做:

  var result = context.dbset.Single(x => x.ID == 10000); 

但是使用查找 p>

  var result = context.dbset.Find(10000); 

导致上面的错误。

解决方案

我已经弄清楚了这个问题,它与派生实体中的不映射属性有关(也可能发生在整个派生类未映射)。我在这个答案中更好地表达了他的看法。


I am writing an ASP.Net app using EF6 code-first and table per hierarchy

I get this error whenever I attempt to do anything meaningful with my dbcontext (such as a query, update, etc.):

{
  "Message": "An error has occurred.",
  "ExceptionMessage": "An error occurred while preparing the command definition. See the inner exception for details.",
  "ExceptionType": "System.Data.Entity.Core.EntityCommandCompilationException",
  "StackTrace": "  at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver, BridgeDataReaderFactory bridgeDataReaderFactory, ColumnMapFactory columnMapFactory)\r\n  at System.Data.Entity.Core.EntityClient.Internal.EntityProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree, DbInterceptionContext interceptionContext)\r\n  at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.CreateCommandDefinition(ObjectContext context, DbQueryCommandTree tree)\r\n  at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.Prepare(ObjectContext context, DbQueryCommandTree tree, Type elementType, MergeOption mergeOption, Boolean streaming, Span span, IEnumerable`1 compiledQueryParameters, AliasGenerator aliasGenerator)\r\n  at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)\r\n  at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()\r\n  at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)\r\n  at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()\r\n  at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)\r\n  at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\n  at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()\r\n  at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()\r\n  at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\r\n  at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)\r\n  at SealingServer.Controllers.PdfsController.<PostPdf>d__4.MoveNext() in C:\Users\thoma_000\Documents\All Code\SealingServer\SealingServer\Controllers\PdfsController.cs:line 93\r\n--- End of stack trace from previous location where exception was thrown ---\r\n  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n  at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n  at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n  at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n  at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n  at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n  at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n  at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n  at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
  "InnerException": {
    "Message": "An error has occurred.",
    "ExceptionMessage": "The given key was not present in the dictionary.",
    "ExceptionType": "System.Collections.Generic.KeyNotFoundException",
    "StackTrace": "  at System.Collections.Generic.Dictionary`2.get_Item(TKey key)\r\n  at System.Data.Entity.Core.Mapping.ViewGeneration.Structures.MemberDomainMap.GetDomainInternal(MemberPath path)\r\n  at System.Data.Entity.Core.Mapping.ViewGeneration.QueryRewriting.FragmentQueryKB.CreateIsOfTypeCondition(MemberPath currentPath, IEnumerable`1 derivedTypes, MemberDomainMap domainMap)\r\n  at System.Data.Entity.Core.Mapping.ViewGeneration.QueryRewriting.FragmentQueryKB.CreateVariableConstraintsRecursion(EdmType edmType, MemberPath currentPath, MemberDomainMap domainMap, EdmItemCollection edmItemCollection)\r\n  at System.Data.Entity.Core.Mapping.ViewGeneration.QueryRewriting.FragmentQueryKB.CreateVariableConstraintsRecursion(EdmType edmType, MemberPath currentPath, MemberDomainMap domainMap, EdmItemCollection edmItemCollection)\r\n  at System.Data.Entity.Core.Mapping.ViewGeneration.ViewgenContext..ctor(ViewTarget viewTarget, EntitySetBase extent, IList`1 extentCells, CqlIdentifiers identifiers, ConfigViewGenerator config, MemberDomainMap queryDomainMap, MemberDomainMap updateDomainMap, EntityContainerMapping entityContainerMapping)\r\n  at System.Data.Entity.Core.Mapping.ViewGeneration.ViewGenerator.CreateViewgenContext(EntitySetBase extent, ViewTarget viewTarget, CqlIdentifiers identifiers)\r\n  at System.Data.Entity.Core.Mapping.ViewGeneration.ViewGenerator.GenerateDirectionalViewsForExtent(ViewTarget viewTarget, EntitySetBase extent, CqlIdentifiers identifiers, KeyToListMap`2 views)\r\n  at System.Data.Entity.Core.Mapping.ViewGeneration.ViewGenerator.GenerateDirectionalViews(ViewTarget viewTarget, CqlIdentifiers identifiers, KeyToListMap`2 views)\r\n  at System.Data.Entity.Core.Mapping.ViewGeneration.ViewGenerator.GenerateAllBidirectionalViews(KeyToListMap`2 views, CqlIdentifiers identifiers)\r\n  at System.Data.Entity.Core.Mapping.ViewGeneration.ViewgenGatekeeper.GenerateViewsFromCells(List`1 cells, ConfigViewGenerator config, CqlIdentifiers identifiers, EntityContainerMapping containerMapping)\r\n  at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGenerateViews(EntityContainerMapping entityContainerMap, Dictionary`2 resultDictionary)\r\n  at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGetGeneratedViews(EntityContainer container)\r\n  at System.Data.Entity.Core.Common.Utils.Memoizer`2.Result.GetValue()\r\n  at System.Data.Entity.Core.Common.Utils.Memoizer`2.Evaluate(TArg arg)\r\n  at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.ViewDictionary.GetGeneratedView(EntitySetBase extent, MetadataWorkspace workspace, StorageMappingItemCollection storageMappingItemCollection)\r\n  at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.GetGeneratedView(EntitySetBase extent)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.ExpandView(ScanTableOp scanTableOp, IsOfOp& typeFilter)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.ProcessScanTable(Node scanTableNode, ScanTableOp scanTableOp, IsOfOp& typeFilter)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Visit(ScanTableOp op, Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op, Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Visit(FilterOp op, Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r\n  at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.VisitScalarOpDefault(ScalarOp op, Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.VisitNavPropertyOp(PropertyOp op, Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Visit(PropertyOp op, Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.VisitScalarOpDefault(ScalarOp op, Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r\n  at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r\n  at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op, Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Visit(ProjectOp op, Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitRelOpDefault(RelOp op, Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Visit(ProjectOp op, Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.SubqueryTrackingVisitor.VisitChildren(Node n)\r\n  at System.Data.Entity.Core.Query.InternalTrees.BasicOpVisitorOfNode.VisitDefault(Node n)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Process(Dictionary`2& tvfResultKeys)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.PreProcessor.Process(PlanCompiler planCompilerState, StructuredTypeInfo& typeInfo, Dictionary`2& tvfResultKeys)\r\n  at System.Data.Entity.Core.Query.PlanCompiler.PlanCompiler.Compile(List`1& providerCommands, ColumnMap& resultColumnMap, Int32& columnCount, Set`1& entitySets)\r\n  at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver, BridgeDataReaderFactory bridgeDataReaderFactory, ColumnMapFactory columnMapFactory)"
  }
}

EDIT

I started over with a fresh database and I get the same result for any entity. This leads me to believe it has to do with my DbContext. It looks like this:

public class SealingServerContext : DbContext
    {
        public SealingServerContext() : base("name=TFMContext")
        {
            this.Database.Log = Console.Write;
            this.Configuration.LazyLoadingEnabled = false;
        }
    public DbSet<Organization> Organizations { get; set; }

    public DbSet<User> Users { get; set; }

    public DbSet<Role> Roles { get; set; }

    public DbSet<ReviewerRole> ReviewerRoles { get; set; }
    public DbSet<AnnotationTemplate> AnnotationTemplates { get; set; }
    public DbSet<PaperItem> PaperItems { get; set; }
    public DbSet<PaperRaster> PaperRasters { get; set; }

    public DbSet<EngineerRole> EngineerRoles { get; set; }
    public DbSet<Seal> Seals { get; set; }
    public DbSet<Signature> Signatures { get; set; }


    public DbSet<Job> Jobs { get; set; }
    public DbSet<JobFile> JobFiles { get; set; }
    public DbSet<Pdf> Pdfs { get; set; }
    public DbSet<PdfPage> PdfPages { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<AnnotationTemplate>()
            .HasKey(annotationTemplate => annotationTemplate.ID);

        modelBuilder.Entity<JobFile>()
            .HasKey(pdf => pdf.ID);
        modelBuilder.Entity<Pdf>()
            .HasKey(pdf => pdf.ID)
            .HasMany(pdf => pdf.PdfPages)
            .WithRequired()
            .HasForeignKey(pdfPage => pdfPage.Pdf_ID)
            .WillCascadeOnDelete(true);

        modelBuilder.Entity<Job>()
            .HasKey(job => job.ID);
        modelBuilder.Entity<Job>()
            .HasMany(job => job.Files)
            .WithRequired()
            .HasForeignKey(jobFile => jobFile.Job_ID);
        modelBuilder.Entity<Job>()
            .HasMany(job => job.Regions)
            .WithRequired()
            .HasForeignKey(region => region.Job_ID);

        modelBuilder.Entity<Organization>()
            .HasKey(organization => organization.ID)
            .HasMany(org => org.Users)
            .WithRequired()
            .HasForeignKey(user => user.Organization_ID);

        modelBuilder.Entity<PaperItem>()
            .HasKey(paperItem => paperItem.ID);

        modelBuilder.Entity<PaperRaster>()
            .HasKey(paperRaster => paperRaster.ID);

        modelBuilder.Entity<Models.Files.PdfPage>()
            .HasKey(pdfPage => pdfPage.ID);

        modelBuilder.Entity<Region>()
            .HasKey(region => region.ID);

        modelBuilder.Entity<Role>()
            .HasKey(role => role.ID);

        modelBuilder.Entity<EngineerRole>()
            .HasKey(role => role.ID);
        modelBuilder.Entity<EngineerRole>()
            .HasMany(engineerRole => engineerRole.Seals)
            .WithRequired()
            .HasForeignKey(seal => seal.EngineerRole_ID);
        modelBuilder.Entity<EngineerRole>()
            .HasMany(engineerRole => engineerRole.Signatures)
            .WithRequired()
            .HasForeignKey(signature => signature.EngineerRole_ID);

        modelBuilder.Entity<EngineerAdminRole>()
            .HasKey(role => role.ID);

        modelBuilder.Entity<ReviewerAdminRole>()
            .HasKey(role => role.ID);

        modelBuilder.Entity<ReviewerRole>()
            .HasKey(reviewerRole => reviewerRole.ID)
            .HasMany(reviewerRole => reviewerRole.AnnotationTemplates)
            .WithOptional()
            .HasForeignKey(annotation => annotation.ReviewerRole_ID);

        modelBuilder.Entity<Seal>()
            .HasKey(seal => seal.ID);

        modelBuilder.Entity<Signature>()
            .HasKey(signature => signature.ID);

        modelBuilder.Entity<User>()
            .HasKey(user => user.ID);
        modelBuilder.Entity<User>()
            .HasMany(user => user.Roles)
            .WithOptional()
            .HasForeignKey(role => role.User_ID);
    }
}

Edit2

I've been commenting things out and doing db migrations and have narrowed it down to this inheritance hierarchy:

[KnownType(typeof(PaperRaster))]
public class PaperItem
{
    public int ID { get; set; }

    public PointF PdfPosition { get; set; }

    public string ItemType { get; set; }

    public virtual void Move(PointF coordinatesTranslation)
    {
    }

    protected PaperItem(string paperItemType, PointF pdfPosition)
    {
        ItemType = paperItemType;
        PdfPosition = pdfPosition;
    }

    public virtual PaperItem DeepCopy()
    {
        return new PaperItem("PaperItem", new PointF());
    }


    public virtual string ToJson()
    {
        //turn all of my properties into Json
        return "";
    }
}

and its child class:

public class PaperRaster : PaperItem
{
    public string Source { get; set; }
    public string CrossOrigin { get; set; }
    public Matrix Matrix { get; set; }

    public PaperRaster(string source, string crossOrigin, Matrix matrix, PointF pdfPosition)
        : base("Raster", pdfPosition)
    {
        this.Source = source;
        this.CrossOrigin = crossOrigin;
        this.Matrix = matrix;
    }

    public PaperRaster(string json) : base("Raster", new PointF())
    {
        JArray array = JArray.Parse(json);

        JToken type = array[0];
        JToken properties = array[1];
        JToken position = array[2]["pdfPosition"];


        if (type.ToString() != "Raster")
        {
            throw new Exception("Not a PaperRaster");
        }

        var matrix = properties["matrix"];
        this.Matrix = new Matrix(float.Parse(matrix[0].ToString()), float.Parse(matrix[1].ToString()),
            float.Parse(matrix[2].ToString()), float.Parse(matrix[3].ToString()),
            float.Parse(matrix[4].ToString()), float.Parse(matrix[5].ToString()));

        // Custom encoded properties

        // Bottom left point of annotation (that's how iTextSharp inserts it)

        var x = position["x"].ToString();
        var y = position["y"].ToString();

        this.PdfPosition = new PointF()
        {
            X = float.Parse(x),
            Y = float.Parse(y)
        };
    }

    public override void Move(PointF coordinatesTranslation)
    {
        this.Matrix.Translate(coordinatesTranslation.X, coordinatesTranslation.Y);
    }

    public override PaperItem DeepCopy()
    {
        return new PaperRaster(this.Source, this.CrossOrigin, this.Matrix, this.PdfPosition);
    }

    public override string ToJson()
    {
        //turn all of my properties into Json
        return "";
    }
}

If I comment out the child class and do a db migration. Everything goes back to working. What in this inheritance hierarchy causes EF to incorrectly generate the tables

Other Notes

Strange sidenote, doing this works:

var result = context.dbset.Single(x => x.ID == 10000);

However using Find like so:

var result = context.dbset.Find(10000);

causes the error above.

解决方案

I have figure out the problem to me, it was related with a not mapped property inside the derived entity (and could also occurs when the entire derived class is not mapped). I discribed it better in this answer.

这篇关于实体框架6运行时错误:“给定键不存在于字典”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆