我有一个视图的SQL查询。这个观点
SELECT
[ID]
[Name],
[Category],
MIN(OrderDate) as OrderDate,
MIN(DeliveryDate) as DeliveryDate
GROUP BY
[ID], [Name], [Category]
FROM
[OrdersView]
我知道这个查询是正确的,因为我的DBA给了我。但我需要将其转换为LINQ。目前,我有以下内容:
var orders = from o in dataContext.OrdersView
group o by new { o.ID, o.Name, o.Category } into grouping
select new Order() {
ID = grouping.Key.ID,
Name = grouping.Key.Name,
Category = grouping.Key.Category,
OrderDate = ?,
DeliveryDate = ?
};
我的问题是我不知道如何在OrderDate和DeliveryDate上执行MIN函数,并在我的LINQ查询中使用这些值。不幸的是,我无法更改数据库,因为它被锁定了。有人可以指出我正确的方向吗?
谢谢!
答案 0 :(得分:3)
OrderDate = grouping.Min(a => a.OrderDate)
DeliveryDate = grouping.Min(a => a.DeliveryDate)
修改:意外使用o
代替grouping
。那应该为你做。
答案 1 :(得分:1)
var orders = from o in dataContext.OrdersView
group o by new { o.ID, o.Name, o.Category } into grouping
let orderDate = grouping.Min(order => order.OrderDate)
let deliveryDate = grouping.Min(order => order.DeliveryDate)
select new Order() {
ID = grouping.Key.ID,
Name = grouping.Key.Name,
Category = grouping.Key.Category,
OrderDate = orderDate,
DeliveryDate = deliveryDate
};
将来我建议您使用LINQPad来测试您的查询。它允许查看生成的SQL代码。