如何在复杂查询中使用linq将表连接到另外两个表?

时间:2017-07-27 14:23:52

标签: sql linq linq-to-sql

我正在尝试编写一个从几个sql表中收集记录的linq查询。表格及其关系如下图所示。 已经通过表中的主键和外键建立的关系用黑线指定。 红线指定查询仅需要的关系,以便将记录限制为所需的记录。 enter image description here

这是我对linq查询的最佳尝试,但是它确实提供了我预期的更多记录(不相关记录的组合)。

            var query = from wastewater in db.WasteWaters
                    join allowance in db.Allowances on wasterwater.WasteWaterId equals allowance.WasteWaterId
                    join chemical in db.Chemicals on allowance.ChemicalId equals chemical.ChemicalId
                    join sample in db.Samples on wastewater.WasteWaterId equals sample.WasteWaterId
                    join analysissample in db.Analyses on sample.SampleId equals analysissample.SampleId
                    join analysisallowance in db.Analyses on allowance.ChemicalId equals analysisallowance.ChemicalId

                    select new QueryModel
                    {
                        WasteWaterName =  wastewater.WasteWaterName,
                        SampleDescription = sample.SampleDescription,
                        Chemical = chemical.ChemicalName,
                        Result = analysis.AnalysisResult,
                        MaxAllowed = allowance.MaxAllowance
                    };
        return query;

我认为关键点是将“分析”表格加入“样本”加入“津贴”。

当我用sql查询我的数据库时(我肯定会正确地做),结果与linq查询结果不同。所以我的linq查询肯定有问题。根据sql:

SELECT WasteWaters.WastewaterName, Samples.SmplDescription, Chemicals.ChemicalName, Allowances.MaxAllowance, Analyses.Result
FROM ((Chemicals INNER JOIN (WasteWaters INNER JOIN Allowances ON WasteWaters.WasteWaterId = Allowances.WasteWaterId)
ON Chemicals.ChemicalId = Allowances.ChemicalId) INNER JOIN Samples ON WasteWaters.WasteWaterId = Samples.WasteWaterId)
INNER JOIN Analyses ON (Analyses.ChemicalId = Allowances.ChemicalId) AND (Samples.SampleId = Analyses.SampleId);

对此问题的任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

这对你有用吗?

var ans = from c in Chemicals
          join a in Allowances on c.ChemicalId equals a.ChemicalId
          join w in WasteWaters on a.WasteWaterId equals w.WasteWaterId
          join s in Samples on w.WasteWaterId equals s.WasteWaterId
          join a2 in Analyses on new { a.ChemicalId, s.SampleId } equals new { a2.ChemicalId, SampleId = a2.SampleId.Value }
          select new QueryModel {
              WasteWaterName = w.WasteWaterName,
              SampleDesciption = s.SampleDescription,
              Chemical = c.ChemicalName,
              MaxAllowed = a.MaxAllowance,
              Result = a2.Result
          };

答案 1 :(得分:0)

我可能猜测您需要将查询分组为废水,这样您就不会有同一项目的多行。

我不确定,但肯定你离答案还不远。

让我知道。