嵌套的Linq查询在运行时返回错误(无法创建Anonymous类型类型的常量值)

时间:2019-05-14 07:09:55

标签: asp.net-mvc entity-framework linq

在这里您可以找到整个异常https://pastebin.com/gfHdTUKd

                var rangeReports = dbCon.RangeReports.Where(x => x.PatientRegistrationId == pidReg)
                    .Select(x => new { x.TestID, x.Value, x.TestDate })
                    .OrderBy(x => x.TestDate).Distinct().ToList();


                var ReportsData = dbCon.Tests
                        .Select(t => new 
                        {
                            ID = t.ID,
                            Name = t.Name,
                            reports = rangeReports.Where(rr => rr.TestID == t.ID)
                             .Select(rr => new { TestDate = rr.TestDate, Value = rr.Value }).ToList()
                        }).ToList();

如果我从上面的查询中删除下面的代码行,则工作正常,找不到确切的问题。

reports = rangeReports.Where(rr => rr.TestID == t.ID)
                                 .Select(rr => new { TestDate = rr.TestDate, Value = rr.Value }).ToList()

我们将非常感谢您的帮助

谢谢

1 个答案:

答案 0 :(得分:1)

如果首先实现第二个查询,则应解决以下问题:

            var ReportsData = dbCon.Tests
                    .Select(t => new 
                    {
                        ID = t.ID,
                        Name = t.Name
                    })
                    .ToList() //Materialize the query first
                    .Select(t => new 
                    {
                        ID = t.ID,
                        Name = t.Name,
                        reports = rangeReports.Where(rr => rr.TestID == t.ID)
                         .Select(rr => new { TestDate = rr.TestDate, Value = rr.Value }).ToList()
                    }).ToList();