0

Been trying for a while now, but just can't get it to work the way I want. Referring to the code snippet below, I want to include a related table to Bricks (BrickColors). As of now BrickColors are not included and is lazy loaded.

var query = (from ul in DbContext.UserLocs
             join l in DbContext.Locs on ul.LocId equals l.Id
             join lb in DbContext.LocBricks on l.Id equals lb.LocId
             join b in DbContext.Bricks on lb.BrickId equals b.Id
             join bc in DbContext.BrickColors on b.ColorId equals bc.Id
             where ul.UserId == userId
             group new { LocQty = ul.Quantity, LocBrickQty = lb.Quantity, Brick = b } by new { b.BrickId, b.ColorId }
             into data
             orderby data.Key
             select new
             {
                 Brick = data.FirstOrDefault().Brick,
                 Quantity = data.Sum(d => d.LocBrickQty * d.LocQty)
             })
             .AsNoTracking();

If I remove .AsNoTracking() the performance is quite good, because it keeps the BrickColors table in memory, but I want it to be included in the query from the start.

I have tried DbContext.Bricks.Include(b => b.BrickColorAccessor) in the query, but that doesn't work. I think my group new { } is messing something up since I don't include BrickColors there...

  • A projection (`new ...`) always ignores `Include`. Just add a `BrickColorAccessor` property to the `select`. – Gert Arnold Dec 11 '17 at 11:48
  • Problem is that due to DDD design the Color property on the Brick object is private. Ofc I could use reflection anyway... What I want is to the query to include BrickColor right away, but that seems harder than it sounds. :) – user1872017 Dec 11 '17 at 12:00
  • 1
    A have a very clear stance on this: the EF class model is part of the data access layer so its prime responsibility is to facilitate data access. It's *not* a domain model. At best it can *resemble* a domain model. So don't make navigation properties private if that hampers the way you need to collect data. Al these joins are a tell-tale of a poor navigation property structure (or you just forgot to use them). See also: https://stackoverflow.com/a/18113611/861716 – Gert Arnold Dec 11 '17 at 14:09

0 Answers0