Eager Loading in Entity Framework

Eager loading is used to load parent entities along with child entities at one stretch.You can also practice multi level child entities in Eager loading. The keyword to join parent entity and child entity is "Include".Thus it brings all records in one single query.Here is an example, so that you can understand it better. The following example brings out the results of all employees whose employeeid matches with "employeedetails" employeeid.

Example 1: To Fetch particular Employee details


Employee emp = dbContext.Employees.Include("Employeedetails")
.FirstOrDefault(a => a.EmployeeID == Employeeid);

It means to load the queries with its relationship among other entities.So no need to write seperate query for related query
It is achieved using Include().

Example 2:


Using (var context=new CustomerDBEntities())
{
var cust=(from c in context.customers.Include('Address')
where c.customername=='john'
select c).FirstorDefault ();
" }

Example 3:
List all the products related to product details:-


List prod = dbContext.Products.Include("Productdetails").ToList()
foreach (var p in prod) { Console.WriteLine(p.ProductID); foreach (var proddet in c.ProductDetails) { Console.WriteLine("Product Name{0}", proddet.ProductName); } Console.ReadLine(); }

Example 4:
List all the orders related to orderdetails:-

List ord = dbContext.Orders.Include("Orderdetails").ToList()
foreach (var c in ord) { Console.WriteLine(c.OrderDate); foreach (var orderdet in c.OrderDetails) { Console.WriteLine("Unitprice{0}", orderdet.UnitPrice); } Console.ReadLine(); }

Example 5:
List out the car details of all employees:-

List cr = dbContext.Cars.Include("Employees").ToList()