T-SQL查询,例如:
select sum(amount), min(amount), max(amount) from sales where salesdate < getDate()
似乎很难将Linq转化为Entites。
首先猜测我会尝试
var result = from s in entites.Sales where s.SalesDate < DateTime.Today
group s by 1 into g
select new {
AmountSum = g.Sum(x=> x.amount),
AmountMin= g.Min(x=>x.amount),
AmountMax= g.Max(x=>x.amount)}
这实际上是完成t-sql所做同样事情的最好方法吗?显然,EF生成的SQL包含一个组,通过该组可以给我一个关注的时刻。
答案 0 :(得分:1)
您可以通过更改查询来执行此操作 - 使用示例字典来说明:
Dictionary<int, int> sampleDictionary = new Dictionary<int, int>();
sampleDictionary.Add(4, 5);
sampleDictionary.Add(7, 8);
sampleDictionary.Add(1, 2);
var val = new
{
Max = sampleDictionary.Max(x => x.Key),
Min = sampleDictionary.Min(x => x.Key),
Sum = sampleDictionary.Sum(x => x.Key)
};
Console.WriteLine(val);
Console.ReadKey();
这将选择键的最大值,最小值和总和为新的匿名对象。你可以这样写:
var set = entites.Sales.Where(x => x.SalesDate < DateTime.Today);
var val = new
{
Max = set.Max(x => x.Key),
Min = set.Min(x => x.Key),
Sum = set.Sum(x => x.Key)
};