EF 6 query get a single entry from other table

Viewed 36

I am new to EF 6, then I stumble upon this query and I need to modify it to include the data from OrderDelay table. I only intend to get a single row from the database so I tried .Include(m => m.OrderDelay.FirstOrDefault()) instead of .Include(m => m.OrderDelay). But it does not work. Any idea on how to get just a single row for this table?

      var res = await _db                
                .Include(m => m.BusAdd)
                .ThenInclude(b => b.Suburb)
                    .ThenInclude(s => s.State)
                     ........
            .Include(m => m.OrderDelay)
            .AsNoTracking()
            .SingleOrDefaultAsync(p => p.Id == id);


        return res;
1 Answers

it does return a single row from sql the main _db.SingleOrDefaultAsync(p => p.Id == id);

if you use Include() sql-c# translation of outer join it will satisfy the main condition of the Where() and return everything that the included table is linked to.

so it will return

   1 main row that satisfy the main condition of SingleOrDefaultAsync(p => p.Id == id);
       multiple foreign table row

If you are pertaining to only one result _db then do not use/add multiple Include(x => x.TableName)

Just use _db.SingleOrDefaultAsync(p => p.Id == id);

But if you want to have all the Joined tables but only one of each BusAdd, Suburb, State, OrderDelay

then insert .Select() before/after SingleOrDefaultAsync() with conditions of

{
    prop1 = row.prop1,
    prop2 = row.prop2,
    BusAdds = row.BusAdds.FirstOrDefault/SingleOrDefaultAsync(add condition here or none),
    Suburbs = row.Suburbs.FirstOrDefault/SingleOrDefaultAsync(add condition here or none),
    States = row.States.FirstOrDefault/SingleOrDefaultAsync(add condition here),
    OrderDelay = row.OrderDelay.FirstOrDefault/SingleOrDefault(add condition here or none)
}
Related