将SQL转换为LINQ To Entities

时间:2011-08-05 15:22:15

标签: .net entity-framework linq-to-entities

如何从this文章中转换以下SQL:

select type, variety, price
from fruits
where price = (select min(price) from fruits as f where f.type = fruits.type)

我试过这种方式:

ctx.Fruits.
Where(f => f.Price == ctx.CreateObjectSet<Fruit>().
Where(f1 => f1.Type == f.Type).Min(f1 => f1.Price));

但它不起作用,因为ctx.CreateObjectSet无法转换为SQL。

3 个答案:

答案 0 :(得分:2)

为什么不

ctx.Fruits.
Where(f => f.Price == ctx.Fruits.
Where(f1 => f1.Type == f.Type).Min(f1 => f1.Price));

答案 1 :(得分:1)

Michael Sagalovich的答案是给出的SQL的正确答案,但请注意,如果同一类型的多个水果具有相同的最低价格,您将获得该类型的多个条目。

这可能更符合您的需求:每种类型只抓一个价格最低的水果:

ctx.Fruits.GroupBy(f => f.Type)
    .Select(g => g.OrderBy(f => f.Price).FirstOrDefault())

答案 2 :(得分:1)

如果你把它表示为按价格排序,可以通过fruit.type分组,然后“挑选”每组中的第一个水果,可能会更清晰,更容易。而且由于GroupBy保留了订单,您可以先进行排序(或第二次),具体取决于哪种更容易阅读(或者如果重要的话,可以根据性能)。