简体   繁体   English

带有多选和子查询的 EF Core CROSS JOIN

[英]EF Core CROSS JOIN with Multiselect and Sub Query

I have a problem writing a LINQ query using CROSS JOIN on two tables, and subquery in the result.我在两个表上使用CROSS JOIN和结果中的子查询编写 LINQ 查询时遇到问题。

I'll show you the SQL query that I made, and it is working in my PostgreSQL Server:我将向您展示我所做的 SQL 查询,它在我的 PostgreSQL 服务器中运行:

SELECT t2.id, t1.id,
      (
       SELECT COALESCE(avg(t3.value), -1) 
       FROM table3 t3
       LEFT JOIN table4 t4 ON t4.id = t3.tag_id
       LEFT JOIN table5 t5 ON t5.id = t4.device_id
       LEFT JOIN table6 t6 ON t6.id = t4.system_id
       WHERE t4.tag_type_id = 171 --TT Value
       AND t1.id = ANY(t4.control_area)
       AND t6.zone_id = t2.id
       ) 
FROM table1 t1
CROSS JOIN table2 t2
ORDER BY t2.z_index,t1.d_index

And I try now to duplicate this query in EF Core code and this is what I got so far:我现在尝试在 EF Core 代码中复制这个查询,这是我到目前为止得到的:

var ss = ctx.Table1.SelectMany(
                t1 => ctx.Table2,
                (t1, t2) => new
                {
                    T1 = t1.Id,
                    T2 = t2.Id,
                    Value = ctx.Table3
                            .Include(s => s.Table4.Table5.Table6)
                            .Where(s => s.Table4.TagTypeId == 171 
                                    && s.Table4.Table5.ControlArea.Any(a => a == t1.Id)
                                    && s.Table4.Table5.Table6.Zone == t2.Id)

                }).ToList();

When I run this I get the following error:当我运行它时,出现以下错误:

Unable to cast object of type 'System.Linq.Expressions.MethodCallExpression2' to type 
'System.Linq.Expressions.LambdaExpression'.

I'm not sure how can I accomplish this without using ctx.Database.ExecuteSqlRaw("SELECT....");我不确定如何在不使用ctx.Database.ExecuteSqlRaw("SELECT....");

Is there a way to do it?有办法吗?

Thanks in advance, Julian提前致谢, 朱利安

I was able to solve my problem.我能够解决我的问题。 I'm posting this answer with hope that it will help others with similar problem.我发布这个答案希望它能帮助其他有类似问题的人。 The solution is just to add .Average(s=>s.Value) to the end of the subquery.解决方案只是将.Average(s=>s.Value)添加到子查询的末尾。

Something like this:像这样:

var ss = ctx.Table1.SelectMany(
            t1 => ctx.Table2,
            (t1, t2) => new
            {
                T1 = t1.Id,
                T2 = t2.Id,
                Value = ctx.Table3
                        .Include(s => s.Table4.Table5.Table6)
                        .Where(s => s.Table4.TagTypeId == 171 
                                && s.Table4.Table5.ControlArea.Any(a => a == t1.Id)
                                && s.Table4.Table5.Table6.Zone == t2.Id).Average(s=>s.Value)

            }).ToList();

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

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