Entity Framework: Get Model with Linked Models in Many to Many Relationship <p>I'm coming from TSQL + C# land and have been trying to adapt to linq and EF. Many-to-many relationships have been tripping me up. I have models with many-to-many relationships that I want to query from a database. Such as:</p> <pre><code> class Product{ public int ID {get;set;} public string ProductName {get;set;} public virtual ICollection&lt;Tag&gt; Tags {get;set;} } class Tag { public int ID {get;set;} public string TagName {get;set;} public virtual ICollection&lt;Product&gt; Products {get;set;} } </code></pre> <p>I'm able to get a product itself out of the DbContext, and then later fetch it's associated Tags like this:</p> <pre><code>// product exists in memory as a Product with an empty product.Tags var query = from p in db.Product from t in db.Tags where p.ID == product.ID select p.Tags; </code></pre> <p>Then I can assign the product.Tags with the fetched Tags. Obviously, this is very inefficient when dealing with multiple products if I have to query for every product.</p> <p>With linq and EF, I want to be able to get a Product with all of its associated Tags in one round trip to the database. Also, I want to be able to get all Products and their associated Tags (or a filtered list of Products). How do would the linq look?</p> <p>Edit:</p> <p>Ok, after some more fiddling around, I've got this:</p> <pre><code>var query = db.Product.Include("Tags") .Where(p =&gt; p.Tags.Any(t =&gt; t.Products.Select(m =&gt; m.ID).Contains(p.ID))); </code></pre> <p>This is almost what I need. The results are all products with tags. Missing are the products that don't have tags. I think of this as the equivalent of a SQL inner join. I want to left outer join the tags to the product, and return all products with tags optional. How to get all products with their associated tags without excluding products that have no tags?</p> <p>Edit:</p> <p>This was easier than I thought.</p> <pre><code>var query2 = db.Product.Include("Tags").DefaultIfEmpty(); </code></pre> <p>This gets all the products and their respective tags, including products without tags. Hopefully it works for the right reasons...</p>