query entity data model using linq methods

We can write LINQ to Entities and Object services queries as standard query expressions. In this article we will see how to write queries as LINQ methods.

By writing LINQ as methods, we can use the .net feature Lamdas. Lamdas are inline methods and are written using specific syntax.

When using LINQ methods in C#, we need not use the select Command. The below code queries customers based on a condition, using c# LINQ to Entities query using the method based syntax. In the statement

var Customers = context.Customer
         .Where(c => c.Name == "Vam");
we have used Where method which is a LINQ method. The Where method requires a condition as a parameter which we write as a lamda expression. The Lamda expressin starts with a control variable, followed by => and then the expression. The query returns all the customers whose names are "Vam".

using (var context = new SalesOrderManagementEntities())
{
	var Customers = context.Customer
              .Where(c => c.Name == "Vam");
	foreach (var Customer in Customers)
	{
  		Console.WriteLine(String.Format("{0}",
                                  Customer.CustomerId));
	}	
	Console.WriteLine();
	Console.ReadLine();
}
The below is a VB LINQ to Entities query using the method based syntax.

Dim customers = context.Customer . Where(Function ( c ) c.FirstName="Vam")

Observe that the Where method contains an expression and starts with Function and then the condition.

In this article, we have seen how to query Entity Data Model using LINq methods in both C# and VB.Net.