在linq的外部联接中使用过滤器

时间:2016-03-11 21:41:13

标签: c# entity-framework linq

我有以下实体:

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过滤。我试图通过

添加过滤器
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

1 个答案:

答案 0 :(得分:3)

您需要先应用过滤器 join

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查询)。