【发布时间】:2015-08-09 02:28:05
【问题描述】:
我有:
private Dictionary<int, Сolor[]> colorSet = new Dictionary<int, Сolor[]>()
{
{1, new Сolor[2] {Сolor.Red, Сolor.Green}},
{2, new Сolor[2] {Сolor.Yellow, Сolor.Blue}},
...
};
public class Graph
{
public Сolor Сolor { get; set; }
public ICollection<Point> Points { get; set; }
}
1) 我如何从Points 不为空的数据库中获取List<Graph>?
List<Graph> graphs = context.Graphs.Where(g => g.Points.Count > 0).ToList()
2) 如何执行?
List<Graph> graphs = context.Graphs.Where(g => colorSet[1].Contains(g.Color)).ToList()
例外是:
LINQ to Entities无法识别方法 '...' 方法,并且 此方法无法转换为商店表达式。
【问题讨论】:
-
使用
g.Points.Any()将产生比g.Points.Count > 0更有效的查询。它让 SQL 生成if Exists(select 1 from ...)查询而不是if (select count(*) from ...) > 0查询 -
colorSet[1].Contains(g.Color)绝对不会转换为存储表达式或 sql,因为您将 linq to object 与 linq to sql 混合在一起。尝试在 where 之前调用 ToList。 -
@JenishRabadiya 在 where 之前执行 .ToList 会导致他的整个数据库被加载到客户端上。通常不是一个好主意。
-
@ScottChamberlain 没错,但它不适用于 linq to object 和 linq to sql 的混合。或者他需要为此创建存储过程。
-
Color类是什么?是你自己的枚举、枚举还是实体?