Executing SQL Query using LINQ to SQL

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

Explanation

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

clip_image002

ExecuteQuery takes two input parameter

1. SQL Query as string

2. Parameters used in SQL query

clip_image003

And it returns an IEnumerable.

Example

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

clip_image005

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

clip_image007

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

clip_image009

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);
            }

            Console.ReadKey(true);

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

            Console.ReadKey(true);
}
}
}

On pressing F5 you should get output as below,

clip_image002[5]

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

About these ads

3 thoughts on “Executing SQL Query using LINQ to SQL

  1. Pingback: Dew Drop – June 29, 2011 | Alvin Ashcraft's Morning Dew

  2. Pingback: Monthly Report June 2011: Total Posts 33 « debug mode……

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s