简体   繁体   English

带有 JOIN 和 GROUP 的 EF / Linq 查询

[英]EF / Linq query with JOIN and GROUP

I need to create the following TSQL query in EF/Linq but I am struggling :我需要在 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

I have got a basic query working but that obviously give me duplicate lines :我有一个基本的查询工作,但这显然给了我重复的行:

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

How do I achieve what I need in SQL in Linq?如何在 Linq 的 SQL 中实现我需要的功能? I normally use SQL Stored Procs for data retrieval but trying to do this project all in EF/Linq.我通常使用 SQL 存储过程进行数据检索,但试图在 EF/Linq 中完成这个项目。

Thanks for that - initially it was generating an error :谢谢你 - 最初它产生了一个错误:

The LINQ expression 'DbSet\r\n .Where(m => m.PropertyID == __id_0)\r\n .Join(\r\n outer: DbSet, \r\n inner: 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)' could not be translated. 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)' 无法翻译。 Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().以可翻译的形式重写查询,或通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用显式切换到客户端评估。 See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.有关详细信息,请参阅https://go.microsoft.com/fwlink/?linkid=2101038

I changed it slightly and now it seems to work :我稍微改变了它,现在它似乎工作了:

 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();

Got some reading to do to understand why!需要阅读以了解原因!

that may be useful...这可能有用...

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