My where clause doesn't apply on my result

让人想犯罪 __ 提交于 2019-12-13 07:52:57

问题


I have this query

_ctx.TestPackageReportDetails.GroupBy(i => new {i.Status, i.TestPackageId})
                .Where(m => m.Count(i => i.Status == "Accept") == 5)

The result :

And this query :

  var q2 = _ctx.TestPackages.ToList();

Now i create a join between two result :

 _ctx.TestPackageReportDetails.GroupBy(i => new { i.Status, i.TestPackageId })
                .Where(m => m.Count(i => i.Status == "Accept") == 5)
                .Join(_ctx.TestPackages, i => i.Key.TestPackageId, m => m.Id, (i, m) => new { pack = m, det = i })
                .Sum(i => i.pack.Size);

I create a joint based on testpackageid and i need the sum of size value with this condition Where(m => m.Count(i => i.Status == "Accept") == 5),but it doesn't work ,and the query calculates all package size not the package size with this condition Where(m => m.Count(i => i.Status == "Accept") == 5)


回答1:


You need to filter out the records with the status that you don't need. Also you need to start to make use of the Elegant Query-Syntax which is more readable. Like this:

var sum = (from i in _ctx.TestPackageReportDetails
           where i.Status == "Accept"
           group i by new { i.Status, i.TestPackageId } into grouping
           where grouping.Count() == 5
           join m in _ctx.TestPackages
           on grouping.Key.TestPackageId equals m.Id
           select m.Size).Sum();



回答2:


You´ve got a problem with either your connectionstring, your database or your code. The reason for this error when you remove Sum() is because after removing this the execute of this LINQ Statement is deferred when you first call a function that executes it. This could be a foreach or a toList() or something similar. In one of your calling methods EntityFramework internally opens another DataReader so if you want to solve this problem you should check up if your connectionstring has the MultipleActiveResultSets Option enabled.

Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;MultipleActiveResultSets=true;

If you enable this, you should be able to open multiple DataReaders at once.



来源:https://stackoverflow.com/questions/38951511/my-where-clause-doesnt-apply-on-my-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!