简体   繁体   中英

Lambda expression for outer joins

I want to write a lambda equivalent for

from col in db.Collectors
  join f in db.Files
on new { col.CollectorCode, col.StatusID }
  equals new { f.CollectorCode, StatusID = 1 } into f_join
from f in f_join.DefaultIfEmpty()
where
  col.FileID == null
orderby
  col.CollectorCode
select new {
  col.CollectorCode,
  col.Name
}

I have a table collector and table file. Table files contains multiple records(files) for each collector and I want to retrieve only the collectors that do not have records in table files.

I am not clear how to do it.

This is what I have, but is not working as expected:

db.Collectors.Join(
                db.Files,
                col => col.CollectorCode,
                f => f.CollectorCode,
                (col, f) => new { Collector = col });

The join ... into query syntax code corresponds to GroupJoin , not Join .

db.Collectors.GroupJoin(
    db.Files,
    col => col.CollectorCode,
    f => f.CollectorCode,
    (col, f_join) => new { col, f_join })

And any from clauses after the first will correspond to SelectMany :

db.Collectors.GroupJoin(...)
    .SelectMany(join => join.f_join.DefaultIfEmpty().Select(f => new{join.col, f}))
    //...

Personally, with a query like this that needs to propagate information projected from previous operations "past" another operation tends to be much clearer in query syntax than method syntax, due to the need in method syntax here to constantly be projecting everything out into anonymous types with all of the pieces of data to hold onto.

Sounds like a simple Where clause:

db.Collectors.Where(c => !db.Files.Any(f => f.CollectorCode == c.CollectorCode));

I use Any in the inner query so it will "short-circuit" when a match is found. There may be a more efficient approach, but this will work.

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