LINQ JOIN有3个表,其中两个表有多对一的关系

时间:2017-11-08 20:06:47

标签: c# linq

HY。我正在处理一个查询,它应该加入3个表,比如

  • 客户 - 有身份证明 - 以他的名字命名
  • 银行业务 - 已经过时 - 从bankDate获取一些数据到bankDate
  • 营销 - 已经克服了 - 从marketDate到marketDate
  • 获取一些数据

代码:

var totals = from client in _db.Clients
                join bank in _db.Banking on client.Id equals bank.ClientId
                where (client.Id == bank.ClientId  &&
                       DateTime.Compare(bank.BankDate, (DateTime) fromDate) >= 0 &&
                       DateTime.Compare(bank.BankDate, (DateTime) toDate) <= 0)
                join market in _db.Marketing on client.Id equals market.ClientId
                where (client.Id == market.ClientId && 
                       DateTime.Compare(market.MarketDate, (DateTime) fromDate) >= 0 &&
                       DateTime.Compare(market.MarketDate, (DateTime) toDate) <= 0)
                select new {client.Username, bank, market};

该算法不能为具有多对一关系的表提供成功的连接。 谁曾遇到过这个问题,知道如何解决这个问题?我会非常感激您的帮助

2 个答案:

答案 0 :(得分:0)

我假设where语句没有引用正确的表。

试试这个:(可能是语法错误)

var totals = from client in _db.Clients
        join bank in _db.Banking.Where(x => DateTime.Compare(x.BankDate, (DateTime) fromDate) >= 0 &&
                DateTime.Compare(x.BankDate, (DateTime) toDate) <= 0) on client.Id equals bank.ClientId
        join market in _db.Marketing.Where(x => DateTime.Compare(x.MarketDate, (DateTime) fromDate) >= 0 &&
                DateTime.Compare(x.MarketDate, (DateTime) toDate) <= 0) on client.Id equals market.ClientId
        select new {client.Username, bank, market};

答案 1 :(得分:0)

多对一,我想你正在寻找左外连接,试试这个。

var totals = from client in _db.Clients
                         join bank in _db.Banking on client.Id equals bank.ClientId into banks
                         from bank in banks.DefaultIfEmpty()
                         where (client.Id == bank.ClientId &&
                                DateTime.Compare(bank.BankDate, (DateTime)fromDate) >= 0 &&
                                DateTime.Compare(bank.BankDate, (DateTime)toDate) <= 0)
                         join market in _db.Marketing on client.Id equals market.ClientId into markets
                         from market in markets.DefaultIfEmpty()
                         where (client.Id == market.ClientId &&
                                DateTime.Compare(market.MarketDate, (DateTime)fromDate) >= 0 &&
                                DateTime.Compare(market.MarketDate, (DateTime)toDate) <= 0)
                         select new { client.Username, bank, market };