Explain Codes LogoExplain Codes Logo

What is the syntax for an inner join in LINQ to SQL?

sql
join
linq
sql-server
Alex KataevbyAlex Kataev·Sep 15, 2024
TLDR

Here's a primer on using join in LINQ to construct an Inner Join:

var query = from c in context.Customers join o in context.Orders on c.ID equals o.CustomerID select new { c.Name, o.OrderDate };

This maps Customers with Orders by aligning on IDs, and extracts Name and OrderDate.

Crafting Results with Anonymous Objects

Craft concise queries and customized results using anonymous objects:

from product in context.Products join sale in context.Sales on product.ID equals sale.ProductID select new { product.Name, sale.Date, sale.Quantity }; // Voila! You handpicked the result!

You can also tap into navigation properties as a breather from join. Here, Product is a subentity of the Sale class:

from sale in context.Sales select new { sale.Product.Name, sale.Date, sale.Quantity }; // look Ma, no joins!

Multi-condition Joins: Double the Fun!

&& operator comes handy when you yearn to constrain on multiple fields:

from c in context.Customers join o in context.Orders on c.ID equals o.OrderID && c.Region equals o.ShipRegion select new { c.Name, o.OrderDate }; // i.e. find me customers who forgot their orders in the same region!

Turbocharged Joins with .Join() Method

To add more fine-grain control and readability, choose the .Join() method:

context.Customers .Join(context.Orders, customer => customer.ID, order => order.CustomerID, (customer, order) => new { customer.Name, order.OrderDate }); // That's some lambda magic right there!

Query Optimization Toolkit

Pin-point Projections

While sculpting your select statement, sieve out the gems for leaner data:

select new { c.Name, c.Email, o.TotalAmount }; // I want only these! No more, no less.

Lay Back with Deferred Execution

Use the lazy (but smart) way with deferred execution. LINQ queries don't rush to execute, perfect for late refinements:

var query = from c in context.Customers join o in context.Orders on c.ID equals o.CustomerID select new { c, o }; // ... Anytime later var filteredQuery = query.Where(c => c.o.TotalAmount > 100).ToList(); // snooze anda execute!

Sense-making with Enumerations

Decode your integers with enumerations for relevance and readablility in results:

select new { Status = (OrderStatus)o.Status, o.OrderDate }; // Who knew 1 meant 'In Progress' all this while?