LINQ to Entity : Querying data using ADO.NET Entity Framework

ADO.NET Entity Framework have evolved since we have released it first time. Now with the Visual Studio 2008 if you install the .NET Framework 3.5 SP1 and Visual Studio 2008 SP1 you will get the fully functional version of ADO.NET Entity Framework. This is post Beta 3 release.

To create a .edmx file you have template in Visual Studio 2008,

Project > Add New Item

image

 image

image

image

image

After creating the .edmx file, write the below query,

using (ObjectContext objC = new ObjectContext("name=NorthwindEntities"))

{

ObjectQuery<Customers> custs =

objC.CreateQuery<Customers>("NorthwindEntities.Customers");

foreach (Customers cust in custs)

{

Console.WriteLine(cust.CompanyName);

}

}

Note that this returns Object ObjectQuery<T> which implements IQueryable<T>, which means it will also allow you to write LINQ and this LINQ supports external source. Meaning it will translate the code to T-SQL (if you use MS SQL Server database).

I feel more comfortable if I use LINQ,

using (ObjectContext objC = new ObjectContext("name=NorthwindEntities"))

{

var custs = from c in

objC.CreateQuery<Customers>("NorthwindEntities.Customers")

where c.City == "London"

select c;

foreach (Customers cust in custs)

{

Console.WriteLine(cust.CompanyName);

}

}

Now this is already strongly typed and I do not have to use ObjectContext and ObjectQuery anymore.

So my pure LINQ to Entity will look like,

using (NorthwindEntities db = new NorthwindEntities())

{

var custs = from c in db.Customers

where c.City == "London"

select c;

foreach (Customers cust in custs)

{

Console.WriteLine(cust.CompanyName);

}

}

Namoskar!!!