选择列和大于x的实体框架

本文关键字:实体 框架 大于 选择 | 更新日期: 2023-09-27 18:18:03

我有一个sql表,其中有一个唯一Id的许多成本条目。

下面是该表的简化版本:

Table:
{
 public int Id {get;set;}
 public DateTime date {get;set;}
 public int Cost {get;set;}
}

我需要构建一个EF查询来执行以下操作:

select from the table where x.date.Date = DateTime.Now.date && SUM(x.cost) > 100.00)
and it should group by x.Id

选择列和大于x的实体框架

您需要做几件事。对于数据,获取开始结束时间和日期范围要比只获取日期组件简单得多。其次,只需应用第二个Where来过滤掉SUM() > 100:

var dateToCheck = DateTime.Now;
var start = dateToCheck.Date;
var end = dateToCheck.AddDays(1).Date;
var data = tables
    .Where(t => t.date >= start && t.date < end)
    .GroupBy(t => t.Id)
    .Where(g => g.Sum(t => t.Cost) > 100);

您对DavidG的帖子的附加评论

这可能是你要找的

var date = DateTime.Now;
var data = from entry in tables
           where entry.Date.Month == date.Month && entry.Date.Year == date.Year
           group entry.Cost by entry.Id into g
           where g.Sum() > 100
           select new { Id = g.Key, Sum = g.Sum() };