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

时间:2018-04-20 04:36:54

标签: c# mysql .net entity-framework entity-framework-6

我正在使用MySQL的Entity Framework。假设我有以下实体:

  • Country
    • State
      • City
        • Car
        • Building

要急切地包括Cars,我可以使用以下内容:

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

同样,要一直包括Buildings,我可以使用:

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

他们都工作得很好。现在,我想将这两者结合起来,以便同时包含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();

但每当我将两者结合在一起 - 使用上面的代码 - 时,它会在内部异常中抛出以下消息EntityCommandExecutionException异常

  

{“'字段列表'中的未知列'Apply1.Id'”}

我花了两个小时试图弄清楚查询有什么问题,最后,我决定用SQL Server测试它,它没有任何问题。

总结一下我的问题:

  • 知道为什么这不适用于MySQL吗?查询本身有问题吗?
  • 是否有任何解决方法/替代方法可以通过MySQL实现此目的?

请注意,这只发生在第三级(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();

以下是相关案例的完整例外情况:

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: 

1 个答案:

答案 0 :(得分:2)

正如@IvanStoev所指出的那样已经是Reported Bug,但更好的问题是为什么要调用产生笛卡儿生产的查询。从entityframework中包含多个数据集通常不是一个好主意。即

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();

此查询将撤回其中的数据集,每1个建筑物中您拥有所有可能的汽车并包含城市信息。你在浪费资源。相反,你应该加载单独的集合,这将避免错误。并以最小的开销加载您的相关实体。最好你应该调用它,这也可以作为一种解决方法:

//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()

您可以决定在包含中的国家/地区加载说明状态,但是您不应该堆叠多对多的嵌套,因为它可能会增加数量