如何在Linq查询中使用.ToList()?

时间:2014-10-10 20:37:57

标签: linq linq-to-sql

我有一个包含列表项的类。我想要一个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 个答案:

答案 0 :(得分: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.AvailableColors的类型更改为IEnumerable<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)
        };
相关问题