Partilhar via


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!!!

Comments

  • Anonymous
    October 22, 2008
    IMO, when calling k.Orders, the framework should be smart enough to load it on demand without having to call k.Orders.Load, or without having to create a separate query.  So this query would work in both instances: var query = from c in ctx.Customers            where c.City == "London"            select c;

  • Anonymous
    March 09, 2009
    I'm missing something here...I don't have a a ".Include" method, as in: ctx.Customers.Include Any ideas why?

  • Anonymous
    March 10, 2009
    @David, It should be part of. Please share the snippet.

  • Anonymous
    May 13, 2009
    I must be doing something wrong, but my .Include method is working, but my .Load method is not. I am using VB.net on an ASPX page.  My data model, for currnt purposes, has a tblUsers with a UserTypeID related to L_UserType.  The following query successfully loads:   Dim entUsers = (From Users In   userdata.tblUsers.Include("L_UserType")) However, trying the following, indicates there is no Load method:   Dim entUsers = (From Users In   userdata.tblUsers)   entUsers.First.L_UserType.Load The specific message is "Load is not a member of taskManagement.EntityData.L_UserType" (TaskManagement.EntityData is the project containing the data model). Is there a reference I am missing or something?  Thanks so much for your help...this post and the video were very helpful.