首页 > 解决方案 > 根据多个字段从两个表中选择不同的行

问题描述

我需要从一个表中选择另一个表中不存在的行。但是,我无法加入,ID因为这些表来自不同的数据库。

在第一个数据库中,我有一个名为的表Actual在此处输入图像描述

来自不同数据库的第二个表被命名为Forecasts在此处输入图像描述

我对每个数据库都有一个上下文,并使用以下 C# 代码来获取数据:

var forecastRows = targetContext.Forecasts.ToList();
var actualRows = sourceContext.Actual.ToList()
    .Select(actual => new
    {
        TargetMonth = DateTimeExtensions.GetMonthCode(actual.Date.Year, actual.Date.Month),
        CustomerCode = actual.CustomerGroupNo,
        actual.Brand
    });

然后我定义变量以从表中获取行Forecasts,这些行在表中不存在Actual

var orphanActualRows = forecastRows.Where(row => 
    !actualRows.Any(f => f.Brand == row.Brand.Code 
                      && f.CustomerCode == row.Customer.Code 
                      && f.TargetMonth == row.TargetMonth));

但它不能正常工作。它返回表的总数Forecasts。但它不准确,因为行数要少得多......

标签: c#sqllinq

解决方案


我认为这个加入可以帮助你。

  var orpahanActualRows = targetContext.Forecast.Join(
            sourceContext.Actual,
            forecastRows => new { forecastRows.Brand, forecastRows.CustomerCode, forecastRows.TargetMonth },
            actualRows => new { actualRows.Brand, actualRows.CustomerGroupNo, actualRows.Date.Year, actualRows.Date.Month},
            (forecastRows, actualRows) => new { f = forecastRows,  rows=actualRows })
            .Where(d => d.rows.Brand.Code != d.f.Brand
                    && d.rows.CustomerCode != d.f.CustomerCode
                    && rows.TargetMonth != DateTimeExtensions.GetMonthCode(rows.Date.Year, rows.Date.Month))
            .Select(d => d.f)
            .ToList();

推荐阅读