简体   繁体   English

使用多个Include()与嵌套的Select()时的EntityCommandExecutionException

[英]EntityCommandExecutionException when using multiple Include() with nested Select()

I'm using Entity Framework with MySQL. 我正在使用MySQL的实体框架。 Suppose I have the following entities: 假设我有以下实体:

  • Country
    • State
      • City
        • Car
        • Building

To eagerly include all the way down to Cars , I can use the following: 为了热切地包括Cars ,我可以使用以下内容:

context.Countries.
    Include(c => c.States.Select(s => s.Cities.Select(ci => ci.Cars))).ToList();

Similarly, to include all the way down to Buildings , I can use: 同样,要包括一直到Buildings ,我可以使用:

context.Countries.
    Include(c => c.States.Select(s => s.Cities.Select(ci => ci.Buildings))).ToList();

They both work just fine. 他们都工作得很好。 Now, I would like to combine these two in order to include both Cars and Buildings , so I do the following: 现在,我想将这两者结合起来,以包括CarsBuildings ,所以我做了以下几点:

context.Countries.
    Include(c => c.States.Select(s => s.Cities.Select(ci => ci.Cars))).
    Include(c => c.States.Select(s => s.Cities.Select(ci => ci.Buildings))).ToList();

But whenever I combine the two together --using the above code-- , it throws an EntityCommandExecutionException exception with the following message in the inner exception : 但每当我将两者结合在一起- 使用上面的代码 - 时 ,它会在内部异常中抛出一个EntityCommandExecutionException异常并带有以下消息:

{"Unknown column 'Apply1.Id' in 'field list'"} {“'字段列表'中的未知列'Apply1.Id'”}

I spent two hours trying to figure out what's wrong with the query, and finally, I decided to test it with SQL Server and it worked without any problems. 我花了两个小时试图弄清楚查询有什么问题,最后,我决定用SQL Server测试它,它没有任何问题。

To sum up my questions: 总结一下我的问题:

  • Any idea why this doesn't work with MySQL? 知道为什么这不适用于MySQL吗? And Is there something wrong with the query itself? 查询本身有问题吗?
  • Is there any workaround/alternative to achieve this with MySQL? 是否有任何解决方法/替代方案来实现这一点与MySQL?

Please note that this only happens at the third level (the second level of Select ), for example, the following would work just fine: 请注意,这只发生在第三级( Select的第二级),例如,以下内容可以正常工作:

context.Countries.
    Include(c => c.States.Select(s => s.Cities.Select(ci => ci.Cars))).
    Include(c => c.States.Select(s => s.Laws.Select(l => l.PrivacyLaws))).ToList();

Here's the full exception details in case it's relevant: 以下是相关的完整异常详细信息:

System.Data.Entity.Core.EntityCommandExecutionException was unhandled
  HResult=-2146232004
  Message=An error occurred while executing the command definition. See the inner exception for details.
  Source=EntityFramework
  StackTrace:
       at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
       at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
       at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
       at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
       at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
       at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation)
       at System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
       at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
       at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
       at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       at ConsoleApplication1.Program.Main(String[] args) in E:\Test\tmpEF\tmpEF\Program.cs:line 15
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
       ErrorCode=-2147467259
       HResult=-2147467259
       Message=Unknown column 'Apply1.Id' in 'field list'
       Number=1054
       Source=MySql.Data
       StackTrace:
            at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
            at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
            at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
            at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
            at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
            at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
            at MySql.Data.Entity.EFMySqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
            at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
            at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)
            at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
            at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
            at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
            at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
            at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
       InnerException: 

As @IvanStoev points out this already is a Reported Bug , but a better question is why do you call a query that produces cartesian production. 正如@IvanStoev所指出的那样,已经是一个报告错误 ,但更好的问题是为什么你会调用产生笛卡尔生产的查询。 Its usually not a good Idea to include multiple data set from entityframework. 从entityframework中包含多个数据集通常不是一个好主意。 IE IE

context.Countries.
    Include(c => c.States.Select(s => s.Cities.Select(ci => ci.Cars))).
    Include(c => c.States.Select(s => s.Cities.Select(ci => ci.Buildings))).ToList();

this query will pull back a data set in it, for every 1 Building you have every possible car and include the city Information. 此查询将撤回其中的数据集,每1个建筑物中您拥有所有可能的汽车并包含城市信息。 You are vastly wasting resources. 你在浪费资源。 Instead you should load the collections seperate, this will avoid the bug. 相反,你应该加载单独的集合,这将避免错误。 and load your related entities with minimal overhead. 并以最小的开销加载您的相关实体。 Optimally you should call this, which will also work as a Work Around: 最好你应该调用它,它也可以用作解决方法:

//You probably want to filter to the countries that have states
var countriesQuery = context.Countries.AsQueryable();
var statesQuery = countriesQuery.SelectMany(x => x.States);
statesQuery.Load();

var cityQuery = statesQuery.SelectMany(x => x.Cities);
cityQuery.Load();
cityQuery.SelectMany(x => x.Cars).Load();
cityQuery.SelectMany(x => x.Buildings).Load();
return countriesQuery.ToArray()

You may make the decision to load say states with the countries in the include, but you shouldn't pile on nested many to many because it can grow in magnitude 您可以决定在包含中的国家/地区加载说明状态,但是您不应该堆叠多个嵌套,因为它的数量会增加

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM