繁体   English   中英

带有 JOIN 和 GROUP 的 EF / Linq 查询

[英]EF / Linq query with JOIN and GROUP

我需要在 EF/Linq 中创建以下 TSQL 查询,但我很挣扎:

SELECT mi.CategoryID, cat.Category
FROM tblPropertyMaintenanceItem mi
INNER JOIN tblCategory cat
ON cat.CategoryID = mi.CategoryID
WHERE mi.PropertyID = 451
GROUP BY mi.CategoryID, cat.Category
ORDER BY cat.Category

我有一个基本的查询工作,但这显然给了我重复的行:

var cats = context.MaintenanceItems
    .Include(s => s.Category)
    .Where(s => s.PropertyID == id)
    .OrderBy(s => s.Category.CategoryName).ToList();

如何在 Linq 的 SQL 中实现我需要的功能? 我通常使用 SQL 存储过程进行数据检索,但试图在 EF/Linq 中完成这个项目。

谢谢你 - 最初它产生了一个错误:

LINQ 表达式 'DbSet\r\n .Where(m => m.PropertyID == __id_0)\r\n .Join(\r\n 外部:DbSet,\r\n 内部:m => EF.Property< Nullable>(m, "CategoryID"), \r\n outerKeySelector: c => EF.Property<Nullable>(c, "CategoryID"), \r\n innerKeySelector: (o, i) => new TransparentIdentifier<MaintenanceItem , Category>(\r\n Outer = o, \r\n Inner = i\r\n ))\r\n .GroupBy(\r\n source: m => m.Inner, \r\n keySelector : m => m.Outer)' 无法翻译。 以可翻译的形式重写查询,或通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用显式切换到客户端评估。 有关详细信息,请参阅https://go.microsoft.com/fwlink/?linkid=2101038

我稍微改变了它,现在它似乎工作了:

 var cats = context.MaintenanceItems
            .Include(s => s.Category)
            .Where(s => s.PropertyID == id).AsEnumerable()
            .GroupBy(x => x.Category)
            .Select(x => x.First())
            .OrderBy(s => s.Category.CategoryName).ToList();

需要阅读以了解原因!

这可能有用...

var cats = context.Categories
.Include(s => s.MaintenanceItems)
.Where(s => s.MaintenanceItems.Any(y => y.PropertyID == id))
.Select(s => new { s.CategoryID, s.CategoryName });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM