[英]LINQ JOIN with 3 tables where two of them have many-to-one relations
Hy. HY。 I'm working on a query, which should join 3 tables like
我正在处理一个查询,它应该连接3个表,例如
code: 码:
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};
This algorithm doesn't provide successful join for the tables with many-to-one relations. 该算法无法为具有多对一关系的表提供成功的联接。 Who has ever faced this problem and knows how to solve it?
谁曾经面对过这个问题并且知道如何解决呢? I'll be very appreciated for any help
如有任何帮助,我将不胜感激
I am assuming that the where
statement is not referencing the correct table. 我假设
where
语句未引用正确的表。
Try this: (might be syntax error) 试试这个:(可能是语法错误)
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};
By many-to-one I guess you are looking for left outer join, try this. 通过多对一的方式,我猜您正在寻找左外部联接,请尝试此操作。
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 };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.