Click here to Skip to main content
15,881,139 members
Articles / Web Development / ASP.NET

Six simple steps to use a Stored Procedure in LINQ

Rate me:
Please Sign up or sign in to vote.
4.24/5 (20 votes)
7 Jul 2009CPOL3 min read 194.5K   3.6K   87   8
Six simple steps to use a Stored Procedure in LINQ.

Table of contents

Introduction

This is an extremely small article which describes how to flourish LINQ objects using a Stored Procedure. What provoked me to write this article is the ExecuteMethodCall function which helps to execute Stored Procedures in LINQ. As this is a protected function, it changes the way you architect the DAL using the DataContext class and probably you would like to tweak and consider some options here. You will see more details when you read through the steps below. I am writing a huge series of LINQ FAQ and these small articles form small sprints to complete the huge FAQ series. I hope you enjoy it.

LINQ basics

This article assumes that you have a basic knowledge of how entity objects can be flourished using LINQ. In case you are not aware of the basics of LINQ to SQL mapping, you can read my article to understand the basic LINQ concepts from OneManyandOneOneLINQ.aspx.

Step 1: Create a Stored Procedure

Below is the Stored Procedure which we will use to flourish LINQ objects:

SQL
Create PROCEDURE dbo.usp_SelectCustomer
AS
Select CustomerId,CustomerCode,CustomerName from Customer
RETURN

Step 2: Create a LINQ Entity

The above Stored Procedure returns CustomerId, CustomerCode, and CustomerName, so we need to prepare a LINQ entity as per the returning Stored Procedure data. In case you are not aware of LINQ entities, please read the basics at OneManyandOneOneLINQ.aspx.

C#
[Table(Name = "Customer")]
public class clsCustomerEntity
{
    private int _CustomerId;
    private string _CustomerCode;
    private string _CustomerName;

    [Column(DbType = "nvarchar(50)")]
    public string CustomerCode
    {
        set
        {
            _CustomerCode = value;
        }
        get
        {
            return _CustomerCode;
        }
    }

    [Column(DbType = "nvarchar(50)")]
    public string CustomerName
    {
        set
        {
            _CustomerName = value;
        }
        get
        {
            return _CustomerName;
        }
    }

    [Column(DbType = "int", IsPrimaryKey = true)]
    public int CustomerId
    {
        set
        {
            _CustomerId = value;
        }
        get
        {
            return _CustomerId;
        }
    }
}

Step 3: Inherit from the DataContext class

In order to execute Stored Procedures, LINQ has provided an ExecuteMethod call function which belongs to the DataContext class. This function returns an ISingleresult of an entity collection. The ExecuteMethod call function is a protected function and can only be invoked through inheritance. Methods and functions from which we call our Stored Procedures normally forms our DAL. In other words, ExecuteMethod should be a part of our DAL.

As said, the function is purely protected, you can only invoke it by inheritance and not aggregation. I am really not sure why this compulsion is put by Microsoft, in other words, we need to create an extra class which inherits from DataContext and then put in the corresponding function calls for Stored Procedures. Below is the code snippet where we inherit from the DataContext class and create a new DAL class called ClsMyContext.

C#
public class clsMyContext : DataContext
{}

Step 4: Attribute using the Function attribute

We have created the GetCustomerAll function which is attributed with the Function attribute from the System.Data.Linq.Mapping namespace. The Function attribute has a name parameter which specifies the Stored Procedure name; currently the Stored Procedure is usp_SelectCustomer, as defined in the previous steps.

The IsComposable parameter defines whether this method call is for a Stored Procedure or UDF, i.e., User Defined Function. If IsComposable is false, that means it’s a Stored Procedure, and if it is true, that means it’s a user defined function.

C#
[Function(Name = "usp_SelectCustomer", IsComposable = false)]
public ISingleResult<clsCustomerEntity> getCustomerAll()
{
}

Step 5: Invoke the Executemethod call

Now it’s time to fill in the empty function GetCustomerAll. Below is the code snippet to execute the ExecuteMethod call. This invocation returns back an IExecuteResult object.

C#
IExecuteResult objResult = this.ExecuteMethodCall(this,(MethodInfo)(MethodInfo.GetCurrentMethod()));

The object returned from IExecuteResult has a ReturnValue property from which we can get the results collection of the ClsCustomerEntity type.

C#
ISingleResult<clsCustomerEntity> objresults = (ISingleResult<clsCustomerEntity>) objResult.ReturnValue;

Below is the complete code snippet with the function:

C#
[Function(Name = "usp_SelectCustomer", IsComposable = false)]
public ISingleResult<clsCustomerEntity> getCustomerAll()
{
    IExecuteResult objResult = 
      this.ExecuteMethodCall(this,(MethodInfo)(MethodInfo.GetCurrentMethod()));

    ISingleResult<clsCustomerEntity> objresults = 
        (ISingleResult<clsCustomerEntity>) objResult.ReturnValue;
    return objresults;
}

Step 6: Finally we call the data context in the client

In the final step, we create the context object, call our function, and loop through the object collection display data.

C#
clsMyContext objContext = new clsMyContext(strConnectionString);
foreach(var row in objContext.getCustomerAll())
{
    Response.Write(row.CustomerCode);
}

For further reading do watch the below interview preparation videos and step by step video series.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
GeneralGood work Pin
Menon Santosh6-Dec-13 19:17
professionalMenon Santosh6-Dec-13 19:17 
QuestionDataContext being Open/Closed Pin
Member 1041029618-Nov-13 21:16
Member 1041029618-Nov-13 21:16 
QuestionPassing Parameters? Pin
oalbad13-Jan-12 8:19
oalbad13-Jan-12 8:19 
AnswerMessage Closed Pin
26-Nov-14 19:55
carmel26-Nov-14 19:55 
GeneralMy vote of 3 Pin
prabhatmishra3-Jan-11 22:45
prabhatmishra3-Jan-11 22:45 
QuestionMaster - Detail Entries using Stored Procedures Pin
ravi samsher26-Aug-10 21:00
ravi samsher26-Aug-10 21:00 
QuestionUsing stored procedure in LINQ Pin
Tapas Ranjan Singh14-Sep-09 19:45
Tapas Ranjan Singh14-Sep-09 19:45 
GeneralThank you Pin
EricFromMars14-Jul-09 22:52
EricFromMars14-Jul-09 22:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.