简体   繁体   中英

Left Joins in LINQ with multiple Critieria?

How do you do add additional criteria to your left joins? In LINQ you can have only one join clause "x.id equals y.id". On inner joins, this is no problem, just add them to the where clause. When you are doing a left join this creates issues in LINQ. Adding this additional criteria seems to force it to be an inner join.

join s in db.tblCustomerPricingSchemes on c.CustomerID equals s.CustomerID into g1
from s in g1.DefaultIfEmpty()
join p in db.tblPricingSchemes on l.LangPairs equals p.PSLangPairID into g2
from p in g2.DefaultIfEmpty()
where t.JobID == jobID
    //&& s.PSLangPairID == l.LangPairs
    //&& p.PSDescID == c.PricingID

Any ideas?

Thanks, Steve

from s in db.tblCustomerPricingSchemes
   .where(x => c.CustomerID == x.CustomerID && 
          x.PSLangPairID == l.LangPairs).DefaultIfEmpty()

try

from c in db.tblCustomer
from s in db.tblCustomerPricingSchemes.Where(w => w.CustomerID == c.CustomerID).DefaultIfEmpty()
from p in db.tblPricingSchemes.Where(w => w.PSLangPairID == l.LangPairs).DefaultIfEmpty()
where t.JobID == jobID
select c // etc

You have two options.

Firstly, use the navigational properties. I've asked why people use joins instead of navigational properties a while back and the answers supported my understanding - there's rarely a real reason and it's usually a mistake. As the other answers here suggest, use some where clauses to filter your object graph.

db.tblCustomerPricingSchemes.Where(x => condition).Select(scheme => 
    new { scheme, scheme.LangPair, scheme.LangPair.PricingScheme });

However if you need to join, then you try allowing for the outer join in your where clause by doing some null checks.

where t.JobID == jobID
    && (s.PSLangPairID == null 
        || l.LangPairs == null 
        || s.PSLangPairID == l.LangPairs)
    && (p.PSDescID == null 
        || c.PricingID == null
        || p.PSDescID == c.PricingID)

if it were SQL you use a coalesce operator, but not sure if this would work and again depends on whether you're using LINQ-to-SQL or Entity Framework.

&& (s.PSLangPairID ?? l.LangPairs) == l.LangPairs
&& (p.PSDescID ?? c.PricingID) == c.PricingID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM