Wriju's BLOG

.NET, Cloud and everything

ADO.NET Entity: LINQ to Entity with Relationship

Relationship and getting data from Entity Framework using Northwind database


image



Simple Query


 


using (NorthwindEntities ctx = new NorthwindEntities())


{


    var query = from o in ctx.Orders


                select o.OrderID;


 


    foreach (var k in query)


    {


        Console.WriteLine(k);


    }


}


 


Now if you want to filter this with the parent information,


 


var query = from o in ctx.Orders


            where o.Customers.City == “London”


            select o.OrderID;


This actually goes one level up and then filters the data.


 


Include Child Information


 


var query = from c in ctx.Customers


            where c.City == “London”


            select c;


 


foreach (var k in query)


{


Console.WriteLine(k.ContactName);


}


 


Now if you want to get the “Orders” table, there are two ways to do it,


 


Immediate Loading


 


var query = from c in ctx.Customers.Include(“Orders”)


            where c.City == “London”


            select c;


 


foreach (var k in query)


{


    Console.WriteLine(k.Orders.Count);


}


 


On-Demand Loading


 


var query = from c in ctx.Customers


            where c.City == “London”


            select c;


 


foreach (var k in query)


{


    //if not loaded then load it


    if (!k.Orders.IsLoaded)


        k.Orders.Load();


 


    Console.WriteLine(k.Orders.Count);


}


 


 


Namoskar!!!