Joining in EF Core
Joining allows you to combine data from multiple tables based on related fields using LINQ in EF Core.
Key Topics
Basic Join
Example
using System;
using System.Linq;
class Program
{
static void Main()
{
using (var context = new MyDbContext())
{
var result = context.Employees
.Join(context.Departments,
e => e.DepartmentId,
d => d.Id,
(e, d) => new { e.Name, DepartmentName = d.Name })
.ToList();
foreach (var item in result)
{
Console.WriteLine("Name: " + item.Name + ", Department: " + item.DepartmentName);
}
}
}
}
Explanation: This example demonstrates how to join the Employees
and Departments
tables using LINQ.
Key Takeaways
- Use the
Join()
method to combine data from related tables. - Return a custom object containing combined fields from the joined tables.