2014-10-10 75 views
1

我有一个包含列表项的类。我想要一个linq查询来填充类,包括这个列表。这是我的查询:如何使用.ToList()Linq查询内部?

var query = from c in context.Cars 
      select new CarListItem() 
      { 
       ID = c.ID,      
       Make = c.Make, 
       AvailableColors = context.CarColors.Where(u => u.CarID == c.ID).ToList() 
      }; 

基本上,我想获得所有的汽车列表,包括每个相应的汽车可用的颜色列表。

的问题是,.ToList()的一个错误在查询结果中包含:发生错误:

LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[CarSystem.Models.CarColors] ToList[CarColors](System.Collections.Generic.IEnumerable`1[CarSystem.Models.CarColors])' method, and this method cannot be translated into a store expression. 

在这一点上,我不知道我是否只是用错误的语法在Linq查询中(我应该使用除.ToList()之外的其他东西吗?),或者模型的体系结构可能是错误的。

回答

1

你不能。 EF试图将ToList()转换为SQL,但不知道如何。

你能预料到另一种类型,然后调用ToList()

var query = (from c in context.Cars 
     select new 
     { 
      ID = c.ID,      
      Make = c.Make, 
      AvailableColors = context.CarColors.Where(u => u.CarID == c.ID) 
     }).ToList() 
     .Select(c => new CarListItem() 
     { 
      ID = c.ID,      
      Make = c.Make, 
      AvailableColors = c.AvailableColors.ToList() 
     }); 

或改变CarListItem.AvailableColorsIEnumerable<CarColor>类型:

var query = from c in context.Cars 
     select new CarListItem() 
     { 
      ID = c.ID,      
      Make = c.Make, 
      AvailableColors = context.CarColors.Where(u => u.CarID == c.ID) 
     };