Use a filter in an outer join in linq

Viewed 473

I have the following entities:

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; }
}

I need to get the list of currencies for a country. If a country does not have an entry for a currency I need a line for that missing entry too.

The statement I have right now is:

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 ,
}  ;

This is not filtered by a countryID . I tried to add a filter by

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 

But that does not have a result for a currency that has en entry for a company other then companyID 1.

The cooresponding SQL query would be

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