entity framework6运行时错误:“字典中没有给定键”

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

每当我尝试使用dbcontext执行任何有意义的操作(例如查询,更新等)时,我都会收到此错误:

{ "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.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.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.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.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.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.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.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.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)" } } 

编辑

我从一个新的数据库开始,我得到任何实体的相同结果。 这让我相信它与我的DbContext有关。 它看起来像这样:

 public class SealingServerContext : DbContext { public SealingServerContext() : base("name=TFMContext") { this.Database.Log = Console.Write; this.Configuration.LazyLoadingEnabled = false; } public DbSet Organizations { get; set; } public DbSet Users { get; set; } public DbSet Roles { get; set; } public DbSet ReviewerRoles { get; set; } public DbSet AnnotationTemplates { get; set; } public DbSet PaperItems { get; set; } public DbSet PaperRasters { get; set; } public DbSet EngineerRoles { get; set; } public DbSet Seals { get; set; } public DbSet Signatures { get; set; } public DbSet Jobs { get; set; } public DbSet JobFiles { get; set; } public DbSet Pdfs { get; set; } public DbSet PdfPages { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity() .HasKey(annotationTemplate => annotationTemplate.ID); modelBuilder.Entity() .HasKey(pdf => pdf.ID); modelBuilder.Entity() .HasKey(pdf => pdf.ID) .HasMany(pdf => pdf.PdfPages) .WithRequired() .HasForeignKey(pdfPage => pdfPage.Pdf_ID) .WillCascadeOnDelete(true); modelBuilder.Entity() .HasKey(job => job.ID); modelBuilder.Entity() .HasMany(job => job.Files) .WithRequired() .HasForeignKey(jobFile => jobFile.Job_ID); modelBuilder.Entity() .HasMany(job => job.Regions) .WithRequired() .HasForeignKey(region => region.Job_ID); modelBuilder.Entity() .HasKey(organization => organization.ID) .HasMany(org => org.Users) .WithRequired() .HasForeignKey(user => user.Organization_ID); modelBuilder.Entity() .HasKey(paperItem => paperItem.ID); modelBuilder.Entity() .HasKey(paperRaster => paperRaster.ID); modelBuilder.Entity() .HasKey(pdfPage => pdfPage.ID); modelBuilder.Entity() .HasKey(region => region.ID); modelBuilder.Entity() .HasKey(role => role.ID); modelBuilder.Entity() .HasKey(role => role.ID); modelBuilder.Entity() .HasMany(engineerRole => engineerRole.Seals) .WithRequired() .HasForeignKey(seal => seal.EngineerRole_ID); modelBuilder.Entity() .HasMany(engineerRole => engineerRole.Signatures) .WithRequired() .HasForeignKey(signature => signature.EngineerRole_ID); modelBuilder.Entity() .HasKey(role => role.ID); modelBuilder.Entity() .HasKey(role => role.ID); modelBuilder.Entity() .HasKey(reviewerRole => reviewerRole.ID) .HasMany(reviewerRole => reviewerRole.AnnotationTemplates) .WithOptional() .HasForeignKey(annotation => annotation.ReviewerRole_ID); modelBuilder.Entity() .HasKey(seal => seal.ID); modelBuilder.Entity() .HasKey(signature => signature.ID); modelBuilder.Entity() .HasKey(user => user.ID); modelBuilder.Entity() .HasMany(user => user.Roles) .WithOptional() .HasForeignKey(role => role.User_ID); } } 

EDIT2

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

 [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 ""; } } 

及其子类:

 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 ""; } } 

如果我注释掉子类并执行数据库迁移。 一切都回归工作。 此inheritance层次结构中的内容导致EF错误地生成表

其他说明

奇怪的旁注,这样做有效:

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

但是使用Find就像这样:

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

导致上面的错误。

我已经找到了问题,它与派生实体中的未映射属性有关(并且也可能在未映射整个派生类时发生)。 我在这个答案中更好地描述了它。

我相信这是因为你没有主键,因此只能在主键上使用Find ,因此无法使用。

您可以通过添加符合命名约定的列来隐式设置主键:

 Dog === Id || DogId 

请注意您指定的ID ,因此shell是错误的。

您也可以通过使用[Key]修饰属性来明确设置密钥。