Executing SQL Query using LINQ to SQL

In this post, I will discuss how we can execute a SQL Query directly from LINQ.


To execute SQL query there is a method in DataContext class called ExecuteQuery


ExecuteQuery takes two input parameter

1. SQL Query as string

2. Parameters used in SQL query


And it returns an IEnumerable.


Below code will execute a simple select statement and it will return IEnumerable<Person>


If you want to pass some parameter in the query, you can pass that as second parameter.


If you want pass input parameter as hardcoded value you can very much do that as below


For your reference source code is as below,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.Linq;

namespace Relatedtable
    class Program

        static DataClasses1DataContext context;
        static void Main(string[] args)
            context = new DataClasses1DataContext();

            var result = context.ExecuteQuery<Person>("select * from Person");
            foreach (var r in result)
                Console.WriteLine(r.PersonID + r.FirstName);

            int idToPass = 1;
            var result1 = context.ExecuteQuery<Person>
                          ("select * from Person where PersonID={0}", idToPass);
            foreach (var r in result1)
                Console.WriteLine(r.PersonID + r.FirstName);


            var result2 = context.ExecuteQuery<Person>
                          ("select * from Person where PersonID='1'");
            foreach (var r in result2)
                Console.WriteLine(r.PersonID + r.FirstName);


On pressing F5 you should get output as below,


I hope this post was useful. Thanks for reading Smile

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

3 responses to “Executing SQL Query using LINQ to SQL”

  1. […] Executing SQL Query using LINQ to SQL (Dhananjay Kumar) […]

  2. Nice article.
    What if my context derives from DbContext? I do not see a ExecuteQuery method. Using MVC 3 + EF 4.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com