如何在C#中将指定SQL查询转换为对应的LINQ语句?
SQL转LINQ 按年月分组统计ProviderPosts数量
EF Core 数据库查询写法(可直接翻译为对应SQL执行)
// 写法1:直接按格式化字符串分组,和原SQL逻辑完全对齐 var queryResult = await dbContext.ProviderPosts .GroupBy(post => new { Year = post.CreatedDate.ToString("yyyy"), Month = post.CreatedDate.ToString("MM") }) .Select(group => new { Count = group.Count(), Year = group.Key.Year, Month = group.Key.Month }) .ToListAsync();
若部分EF Core版本无法识别
ToString("yyyy")/ToString("MM")的翻译,可以使用更兼容的写法,先按日期的年、月数值分组再格式化,执行效率和最终结果完全一致:
// 写法2:兼容版本,适配所有EF Core版本 var queryResult = await dbContext.ProviderPosts .GroupBy(post => new { post.CreatedDate.Year, post.CreatedDate.Month }) .Select(group => new { Count = group.Count(), Year = group.Key.Year.ToString(), Month = group.Key.Month.ToString("00") // 补前导零,和原SQL的MM格式对齐 }) .ToListAsync();
内存集合查询写法(针对已加载到内存的ProviderPosts列表)
var memoryResult = providerPostsList .GroupBy(post => new { Year = post.CreatedDate.ToString("yyyy"), Month = post.CreatedDate.ToString("MM") }) .Select(group => new { Count = group.Count(), Year = group.Key.Year, Month = group.Key.Month }) .ToList();
内容的提问来源于stack exchange,提问作者Lujain Alskran
相关产品推荐
相关产品推荐

