Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Linq和ToDictionary的嵌套查询_Linq_Entity Framework - Fatal编程技术网

使用Linq和ToDictionary的嵌套查询

使用Linq和ToDictionary的嵌套查询,linq,entity-framework,Linq,Entity Framework,我在使用实体框架4进行此查询时遇到问题: List<SomeResult> test = (from a in _entities.TableA select new SomeResult { TestB = a.TableB.Name, TestCDict = a.Tabl

我在使用实体框架4进行此查询时遇到问题:

List<SomeResult> test = (from a in _entities.TableA
                         select new SomeResult
                         {
                            TestB = a.TableB.Name,
                            TestCDict = a.TableC.ToDictionary(x => x.SomeKey, x => x.SomeValue)
                          }).ToList();
List test=(来自_entities.table中的
选择新结果
{
TestB=a.TableB.Name,
TestCDict=a.TableC.ToDictionary(x=>x.SomeKey,x=>x.SomeValue)
}).ToList();
它给出了以下错误:

无法比较“System.Data.Objects.DataClasses.EntityCollection`1”类型的元素。只支持基元类型(如Int32、字符串和Guid)和实体类型

如何重做此查询以使其正常工作?从a.a.TableA中的a.a.TableC中的c…到字典(


/Lasse

问题是,您正在对数据库进行查询。而您正在使用的LINQ提供程序实际上并不执行您编写的任何操作。它只是尝试将Select中的所有代码转换为数据库查询。显然,它无法解析真正复杂的状态,就像您使用ToDictionary()编写的那样。 您可以简单地将实体中的所有数据加载到内存中,然后执行所有字典中的工作。然后您的代码将实际执行,并且应该可以正常工作。 比如:

List test=from a in(from aa in_entities.TableA).AsEnumerable())
选择新结果
{
TestB=a.TableB.Name,
TestCDict=a.TableC.ToDictionary(x=>x.SomeKey,x=>x.SomeValue)
}).ToList();

当然,您可以在内部查询中使用DB端过滤(在AsEnumerable()之前),以减少加载到内存中的数据量。

如果我们有超过数百万的数据?那我们该怎么办呢?如果你还想为你的数百万行建立完整的字典,那么你什么也不做。我的回答仍然有效。但我会考虑如何不将所有数据加载到内存中。
List<SomeResult> test = from a in (from aa in _entities.TableA).AsEnumerable())
                         select new SomeResult
                         {
                            TestB = a.TableB.Name,
                            TestCDict = a.TableC.ToDictionary(x => x.SomeKey, x => x.SomeValue)
                          }).ToList();