Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to load many-to-many object graphs using Entity Framework?
    text
    copied!<p>I have a many-to-many relationship (for this example "Left" "Right" and "Joinder") and another entity "Satellite" that keys into "Left." It just so happens that Sattelite's FK also has a unique index on it. My goal is to load one Joinder entity, along with its Left and Right entities, using properties on Satellite for a where clause.</p> <p>I've tried a number of approaches, but my vocabulary for Linq is weak and I don't even really know the terms for what I'm looking for.</p> <pre><code>var joinder = dbContext.Joinders .Include(j =&gt; j.Left) .Include(j =&gt; j.Right) .Include(j =&gt; j.Left.Satellites) .FirstOrDefault(s =&gt; s.Name == "Hubble"); </code></pre> <p>This doesn't work because the FirstOrDefault clause doesn't have context of s to analyze the name.</p> <pre><code>var joinder = dbContext.Joinders .Include(j =&gt; j.Left) .Include(j =&gt; j.Right) .Include(j =&gt; j.Left.Satellites) .Select(j =&gt; j.Left.Satellites) .Where(s =&gt; s.Name == "Hubble"); </code></pre> <p>This doesn't work because the type coming out of Select is <code>IQueryable&lt;Collection&lt;Satellite&gt;&gt;</code> which is confusing.</p> <pre><code>var query = from j in dbContext.Joinders join l in dbContext.Lefts on j.LeftId equals l.Id join r in dbContext.Rights on j.RightId equals r.Id join s in dbContext.Satellites on l.Id equals s.LeftId where s.Name == "Hubble" select j; </code></pre> <p>This query compiles and runs, but returns totally dehydrated objects to me--the Joinder reference I get back has Left and Right properties both null.</p> <pre><code>var query = from j in dbContext.Joinders join l in dbContext.Lefts on j.LeftId equals l.Id join r in dbContext.Rights on j.RightId equals r.Id join s in dbContext.Satellites on l.Id equals s.LeftId where s.Name == "Hubble" select new Joinder { Left = l, Right = r, Left.Satellites = ...? }; </code></pre> <p>This doesn't appear to work because I can't seem to dereference these property names inside an automatic initializer.</p> <p>Anyone know how to do this? Essentially I would like to search "entity framework many-to-many deep load" but I guess not everyone else would word it like me.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload