我正在使用Linq to SQL填充一个类。
我想要做的是查询我的数据库,返回两个整数值并相互减去两个值,产生结果,但我想不出一个聪明的方法来做它。
在这种情况下我该怎么办?
如果不清楚,那么这个伪代码实现应该阐明我希望的功能:
DECLARE @currentVal INT, @previousVal INT
@currentVal = SELECT VALUE
FROM Table1
WHERE Date = CURRDATE()
@previousVal = SELECT VALUE
FROM Table1
WHERE Date = MIN(Date)
RETURN @currentVal - @previousVal
但是在Linq to SQL (from o in context.Table1 where Date = currentDate select Value)
中,如何从中减去其他值?这可能吗?
答案 0 :(得分:2)
我坚持将它作为一组破解的查询,因为您可以测试是否实际返回了值,并处理返回过多值的情况:
var currentValResults = (from row in rows
where row.Date == DateTime.Now
select row.Value)
.ToArray();
var previousValResults = (from row in rows
let minDate = rows.Min(r => r.Date)
where row.Date == minDate
select row.Value)
.ToArray();
if (currentValResults.Length == 1 && previousValResults.Length == 1)
{
var diff = currentValResults[0] - previousValResults[0];
}
else
{
// Error condition?
}
将所有内容放入一个巨大的linq语句中会产生太多假设(至少,我的实现确实如此)。
答案 1 :(得分:0)
这样的事情可以使它保持一次到db(请记住这假设只返回两个结果):
int[] values = (from o in context.Table1
where Date = currentDate || Date = context.Table1.Min(x => x.Date)
order by Date descending
select value).ToArray();
return values[0] - values[1];
答案 2 :(得分:0)
为什么不简单地进行交叉连接
var query=
from a in Table1 where a.Date == DateTime.Now
from b in Table1 where b.Date == Table1.Min(c=>c.Date)
select a.Amount - b.Amount;
var result=query.First();
答案 3 :(得分:0)
var currentVal = context.Table1.FirstOrDefault(t=>t.Date == DateTime.Now.Date);
var previousVal = context.Table1.FirstOrDefault(t=>t.Date == context.Table1.Min(d=>d.Date));
var result = currentVal - previousVal;
或者
from d in context.Table1
let prevVal = context.Table1.FirstOrDefault(t=>t.Date == context.Table1.Min(d=>d.Date));
where d.Date == DateTime.Now.Date
return new { d - prevVal };