Boppity Bop
Boppity Bop

Reputation: 10463

How to include multiple entities with one many-to-many in between

I have 3 tier entities. T <-> TI -> E also TI <- R (where <-> is m..n and -> 1..m)

I need to select a single T with the TI, E and R

without E it works:

var t = dbContext.T
    .Include(i => i.TIs)
    .ThenInclude(i => i.I)
    .ThenInclude(i => i.R)
    .Single(i => i.Id == id);

is it possible to include E without resorting to a for loop?

EDIT thanks to both answers from Canolyb and EspressoBins, although not exactly working, but pushed me to the right track. So the working code is:

var t = dbContext.T
    .Include(i => i.TIs)
    .ThenInclude(i => i.I)
    .ThenInclude(i => i.R)

    .Include(i => i.TIs)
    .ThenInclude(i => i.I.Es)

    .Single(i => i.Id == id);

Upvotes: 0

Views: 397

Answers (2)

Canolyb1
Canolyb1

Reputation: 724

I'm not sure if this is what you're looking for, but to the best of my knowlesge includes can be cascaded like this if you need two ThenIncludes on the same relation.

var t = dbContext.T
  .Include(i => i.TIs)
  .ThenInclude(i => i.I)
  .Include(i => i.TIs)
  .ThenInclude(i => i.R)
  .Single(i => i.Id == id);

If this is not what you're looking for, it would benefit to see your Entity relations / fluent confiugation.

Upvotes: 1

EspressoBeans
EspressoBeans

Reputation: 2015

I had to look at some old code of mine with a similar problem to solve, and forgive me if my relationship directions aren't exact to yours, but does this help you get any closer?
Without using the .ThenInclude()

            var result = dbContext.T
                .Include(t => t.TI)
                .Include(t => t.TI.E)
                .Include(t => t.TI.R)
                .Where(t => t.Id == id)
                .Single();

Upvotes: 1

Related Questions