2016-03-11 27 views
2

我有以下实体:使用在外部过滤器加入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 

添加一个过滤器,但不具有对有恩条目其他然后companyID 1.

公司的货币造成的cooresponding SQL查询是

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

回答

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 s时,其实并不重要组成部分,但对于outer join是很重要的(相同BTW适用于SQL查询)。

+0

Thnx,这两个查询都适合我。我想第一个更容易阅读。 –