在linq的外部联接中使用filter

我有以下实体:

public class Company { public string CompanyName { get; set; } public int ID { get; set; } } public class CompanyCurrency { public int Id { get; set; } public int CompanyId { get; set; } public decimal Rate { get; set; } public int CurrencyId { get; set; } } public class Currency { public int ID { get; set; } public string Name { get; set; } } 

我需要获取一个国家的货币清单。 如果一个国家没有货币的条目,我也需要一条缺失条目的行。

我现在的声明是:

 var currencies = from c in Currencies join cc in CompanyCurrency on c.ID equals cc.CurrencyId into jointable from resultiten in jointable.DefaultIfEmpty() select new {c.Name , HasEntry = resultiten == null ? 0:1, rate = resultiten != null ? resultiten.Rate:0 , } ; 

这不会被countryID过滤。 我试图添加一个filter

 from c in Currencies join cc in CompanyCurrency on c.ID equals cc.CurrencyId into jointable from resultiten in jointable.DefaultIfEmpty() where resultiten.CompanyId == 1 || resultiten == null select new {c.Name , HasEntry = resultiten == null ? 0:1, rate = resultiten != null ? resultiten.Rate:0 

但是,对于除了公司ID 1以外的公司进入的货币,这没有结果。

相应的SQL查询将是

 select * from [dbo].[Currency] c left outer join [dbo].[CompanyCurrency] cc on c.id = cc.Currencyid and cc.[Companyid] = 1 

您需要在join 之前应用filter:

 join cc in CompanyCurrency.Where(e => e.CompanyId == 1) 

或作为加入的一部分

 on new { CurrencyId = c.ID, CompanyId = 1 } equals new { cc.CurrencyId, cc.CompanyId } 

对于inner join它并不重要,但对于outer join它很重要(同样的btw适用于SQL查询)。