LINQ - Creating Query like in SQL

In this article we would learn how to use the Create Query Method in LINQ such that we can create SQL like queries .

This would be particularly useful for those who are used to working in SQL and hence feel LINQ queries are alien to them .

The first step is create a new project lets say a Console Application . And add a ADO.Net Entity Data Model . if you are following my articles , I have explained this step so many times so from now on I will skip explaining this step.

Ok we have added the ADO.Net Entity Data Model . And our Data Model is now ready .

Now lets use the Context object created in the Data Model to create our Query.

The code in the Program class would like as below :

Entities context = new Entities();

Now lets create our Query :

Below is a simple query :

string queryString = @"Select VALUE  c From Entities. PRODUCT As c";

I have highlighted all the keywords . This is pretty easy actually . Once you get used to it .

The SQL version of this Query is :

Select  * from PRODUCT

Okay so we have written our query . Now lets pass it to the CreateQuery() Method and get the Output .

The syntax to pass the Query is given below :

ObjectQuery<PRODUCT> contactQuery = context.CreateQuery<PRODUCT>(queryString,
                new ObjectParameter("",""));

In our case there are no parameters to be passed hence I have just said new ObjectParameter("","") as the second parameter . Passing a Null would throw a error at runtime .

When we run the Program, contactQuery will now have all the data we need .

Similarly we could also implement the Joins using custom Query . The syntax for the custom Joins is given below :

string queryString = @"Select VALUE  d.Company_ID
From Entities.PRODUCT As c
Join Entities.COMPANY As d
On d.Company_ID == c.Company_ID"

In this article we just saw how to implement SQL like queries in .Net using LINQ . Happy Coding