linq group by 和 select inside group by 给出错误 EFcore
Posted
技术标签:
【中文标题】linq group by 和 select inside group by 给出错误 EFcore【英文标题】:linq group by and select inside group by gives error EFcore 【发布时间】:2021-01-01 23:19:17 【问题描述】:我有课
public class statisticsDaily
public string Date get; set;
public Nullable<float> Production get; set;
public Nullable<float> m_wind_speed get; set;
public Nullable<float> Availability get; set;
public string Comments get; set;
public string TurbineId get; set;
public string Countries get; set;
我需要在某个字段上应用聚合函数,并从我的班级中选择其余字段
var rslt = await (from d in db.statMonth.Include(f=>f.MasterData).Where(d=>d.m_turbine_id == IPAddress.Parse(id) && d.m_date >= frm)
group d by new d.m_date.Month, d.m_date.Year into g
select new statisticsDaily
Year = g.Key.Year// We can access Year now since we grouped by Year as well
Date = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(g.Key.Month),
Production = g.Sum(s => s.m_energy_prod),
m_wind_speed = g.Average(s => s.m_wind_speed),
Availability = g.Average(s => s.m_availability),
Comments=g.Select(s=>s.Comments).ToString(),
Countries=g.select(i=>i.Country).ToString()
).OrderBy(s=>s.Date).ToListAsync();
它给了我错误:
LINQ 表达式 'Select
【问题讨论】:
什么是“错误 500”?有没有试过调试代码,看看有没有异常? 那是怎么编译的呢?您的代码中有多个错误。Year
未在 statisticsDaily
上定义,您在分配后缺少 ,
。 Comments=g.Select(i=>s.Comments).ToString()
使用两个不同的变量名
@derpirscher 已编辑,当它想运行 linq 时,它会跳过它
跳过它是什么意思。您是否尝试过调试那段特定的代码并检查是否抛出了异常?
@derpirscher 因错误而更新,通过 try and catch 得到它
【参考方案1】:
这是我可以解决您的查询的最接近的方法。
var rslt =
(
await
(
from d in db.statMonth.Include(f => f.MasterData)
where d.m_turbine_id == IPAddress.Parse(id)
where d.m_date >= frm
group d by new d.m_date.Month, d.m_date.Year into g
orderby g.Key.Month
select new
Year = g.Key.Year,
Date = g.Key.Month,
Production = g.Sum(s => s.m_energy_prod),
m_wind_speed = g.Average(s => s.m_wind_speed),
Availability = g.Average(s => s.m_availability),
Comments = g.Select(s => s.Comments).ToArray(),
Countries = g.Select(i => i.Country).ToArray(),
)
.ToListAsync()
)
.Select(g => new statisticsDaily
Year = g.Year
Date = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(g.Date),
Production = g.Production,
m_wind_speed = g.m_wind_speed,
Availability = g.Availability,
Comments = String.Join(", ", g.Comments),
Countries = String.Join(", ", g.Countries),
)
.ToList();
你能检查一下你现在遇到了什么错误吗?
【讨论】:
@mortezasol - 不,你没有。你没有正确复制我的代码。 State 'IEnumerable以上是关于linq group by 和 select inside group by 给出错误 EFcore的主要内容,如果未能解决你的问题,请参考以下文章
Linq to Entities基础之需要熟知14个linq关键字(from,where,select,group,let,on,by...)
linq group by 和 select inside group by 给出错误 EFcore
LINQ体验——LINQ to SQL语句之Group By/Having和Exists/In/Any/All/Contains
LINQ:从列表中选择项目(Group By/Select/Sum & Max!)