2016-03-11 47 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,這兩個查詢都適合我。我想第一個更容易閱讀。 –