c# – 实体框架6运行时错误:“字典中没有给定键”

c# – 实体框架6运行时错误:“字典中没有给定键”,第1张

概述我正在使用EF6代码优先和每个层次结构的表编写ASP.Net应用程序 每当我尝试使用dbcontext执行任何有意义的 *** 作(例如查询,更新等)时,我都会收到此错误: { "Message": "An error has occurred.", "ExceptionMessage": "An error occurred while preparing the command definit 我正在使用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,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,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,KeyToListMap`2 vIEws)\r\n  at System.Data.Entity.Core.MapPing.VIEwGeneration.VIEwGenerator.GenerateDirectionalVIEws(VIEwTarget vIEwTarget,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,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.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,ColumnMapFactory columnMapFactory)"  }}

编辑

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

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

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

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

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

其他说明

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

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

但是使用Find就像这样:

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

导致上面的错误.

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

以上是内存溢出为你收集整理的c# – 实体框架6运行时错误:“字典中没有给定键”全部内容,希望文章能够帮你解决c# – 实体框架6运行时错误:“字典中没有给定键”所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1226761.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存