When you query for columns in a table , you actually retrieve only the columns from the table you requested. The related tables (Linked/Associations tables ) are not automatically fetched at the same time. suppose you might want to query a customers and a particular set of orders for that customers . you can do this by joining customers and orders in a query by forming the cross-product and retrieving all the relative bits of data as one large Record set. But these results are not entities. when we use LINQ To SQL we can achieved this but In Entity Framework we do not have this options. Now with Entity Framework 4.0 we have it.
setting up the DeferredLoadingEnabled is true in context options
Here is how we can do this. let us create EFM (Entity Framework Model) from the well know DB called North wind. here i am going to use Customer and Order tables .
The above Entity diagram shows Customer and Order relationship is 0 to many.
Now we will query the customer table and display the result on the webpage with out enabling DeferredLoadingEnabled .
protected void Button1_Click(object sender, EventArgs e)
{
using (NorthwindEntities conn = new NorthwindEntities())
{
var query = from cust in conn.Customers
where cust.Country.ToUpper() == "USA"
select cust;
foreach (var item in query.ToList ())
{
Response.Write("Customer ID : " + item.CustomerID + " Total Number of Orders :<b> " + item.Orders.Count.ToString()+"</b></br>");
}
GridView1.DataSource = query.ToList();
GridView1.AutoGenerateColumns = true;
GridView1.DataBind();
}
}
Now we will query the customer table with DeferredLoadingEnabled is set to ture.
protected voidButton1_Click(objectsender, EventArgs e)
{
using(NorthwindEntities conn = newNorthwindEntities())
{
conn.ContextOptions.DeferredLoadingEnabled = true;
var query = fromcust inconn.Customers
wherecust.Country.ToUpper() == "USA"
selectcust;
foreach (var item inquery.ToList ())
{
Response.Write("Customer ID : "+ item.CustomerID + " Total Number of Orders :<b> "+ item.Orders.Count.ToString()+"</b></br>");
}
GridView1.DataSource = query.ToList();
GridView1.AutoGenerateColumns = true;
GridView1.DataBind();
}
}
after setting the DeferredLoadingEnabled =true the query able to bring corresponding order for each customer .
Nandri(Thanks)
SreenivasaRagavan
No comments:
Post a Comment