Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » ADO.NET & Database » Stored Procedure in ADO.NET Data Service

Stored Procedure in ADO.NET Data Service

This Article will explain , how to use stored procedure in Ado.Net Data service

Author Rank :
Page Views : 15132
Downloads : 229
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
StoredProcedureTesting.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Objective:

Objective of this article is to explain, how to use stored procedure with ADO.Net Data Service.
For other articles on ADO.NET Data Service, follow these links

Introduction of ADO.NET Data Service
Working with ADO.NET Data Service

Explanation of Database

For Sample, here database DJ is being used. DJ database is containing two tables

  1. Dept
  2. Emp

Dept

Dept.gif

Emp

Emp.gif

Database Diagram
database.gif

There is Stored Procedure called Get Data. This SP is retrieving all the records from Emp table.

Stored Procedure look more or less like, below

USE [dj]
GO
/****** Object:  StoredProcedure [dbo].[GetData]    Script Date: 05/14/2009 12:12:06 ******/
SET ANSI_NULLS ON
GO
SET
QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:   <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[GetData]
      -- Add the parameters for the stored procedure here

AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
 
    -- Insert statements for procedure here
      SELECT * from Emp
END

Objective of this article is to use this Stored Procedure (GetData) in ADO.NET Data Service.

Step 1

Create a new project as web application and give any name. here name is StoredProcedureTesting.

sptesting.gif

Step 2

Add Data Model.

To do so, add new item and click on Data tab then select ADO.NET Entity Model.

Give any name. Here name is csharp.edmx.

sptesting1.gif

sptesting2.gif

Select database from drop down list. If database in not listed there, create new connection and then select database.

Here database dj is being selected. Schema of database is discussed above.

Give any name to Entity. Here name is storedproceduretestingEntities.

sptesting3.gif

sptesting4.gif

Select the entire table and click on Stored Procedure tab and from there select GetData stored procedure as well. Give any name to model, here it is storedproceduretestingModel

sptesting5.gif

So final edmx file created will look more or less like below.

sptesting6.gif

Step 3

  • Right click on edmx file. Select Add then Function Import.

    sptesting7.gif
     
  • Give Function Import name as of Stored Procedure name. here GetData
     
  • Select Return type. Stored procedure is returning here Emp, so select Emp.

    sptesting8.gif
     
  • In model browser of csharp.edmx , under FunctionImport tab GetData is listed.

    sptesting9.gif

  • In solution explorer, Right Click on csharp.edmx and select open with


    sptesting10.gif


A dialog box will appear. Select XML Editor from there then click on OK.

sptesting11.gif

In Confirmation Box, select YES.

sptesting12.gif

Explanation of markup .edmx file

Markup of edmx file contains three parts or segments.

sptesting13.gif


sptesting14.gif

On selecting stored procedure in entity model, by default below code will get added in SSDL part of markup of .edmx
ssdl segment


<Function Name="GetData" Aggregate="false" BuiltIn="false" NiladicFunction="false" IsComposable="false" ParameterTypeSemantics="AllowImplicitConversion" Schema="dbo" />

Entire SSDL of edmx is,

csdl segment

<FunctionImport Name="Getdata" EntitySet="Emp" ReturnType="Collection(storedproceduretestingModel.Emp)" />

In above XML

Name -> name of the stored procedure

EntitySet -> Entity (Table) on which Stored Procedure is working

ReturnType -> Type of the Return data from Stored Procedure.

If procedure required any parameter, then markup of parameters will be added inside <FunctionImport> like below.

FunctionImport Name ="GetData" EntitySet ="Emp" ReturnType ="Collection(storedproceduretestingModel.GetData)">
 <Parameter Name =""
</FunctionImport>

msl segment

<FunctionImportMapping FunctionImportName="Getdata" FunctionName="storedproceduretestingModel.Store.GetData" />

Up to here Stored Procedure is mapped in entity model.

Step 4

Creating Service

Right click on project and add new item. Add ADO.NET Data Service. Give any name here name is DataService.cs

sptesting15.gif

After this, click on DataService.svc and modify as below

using System;
using System.Collections.Generic;
using System.Data.Services;
using System.Linq;
using System.ServiceModel.Web;
using System.Web;

namespace StoredProcedureTesting
{
    public class DataService : DataService<storedproceduretestingEntities>
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(IDataServiceConfiguration2 config)
        {
            // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
            // Examples:
             config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
            config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
        }
    }
}

Step 5

Testing Service

Right click on DataService and view in browser to test it.

sptesting16.gif

Step 6

Calling stored procedure in ADO.NET Data service

[WebGet]
        public List<Emp> GetData()
        {
            storedproceduretestingEntities ent = new storedproceduretestingEntities();
            return ent.Getdata().ToList();
        }

Explanation of code

Create a new method in DataService class.

Create instance of entities class.

Call the stored procedure which is imported as function on instance of entity class.

Complete code for DataService class is as below

DataService.svc.cs

using System;
using System.Collections.Generic;
using System.Data.Services;
using System.Linq;
using System.ServiceModel.Web;
using System.Web;

namespace StoredProcedureTesting
{
    public class DataService : DataService<storedproceduretestingEntities>
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(IDataServiceConfiguration2 config)
        {
            // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
            // Examples:
             config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
            config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
        }

        [WebGet]
        public List<Emp> GetData()
        {
            storedproceduretestingEntities ent = new storedproceduretestingEntities();
           return ent.Getdata().ToList();

         }
    }
}


Step 7

Testing Stored Procedure in browser

Run the service in browser.

Give GetData function name in browser to run the stored procedure. Let service is hosted on server 2989 then run stored procedure as
http://localhost:2989/DataService.svc/GetData  , output would be like below

sptesting17.gif

Step 8

Consuming Stored Procedure at client

Here console application is client which is going to consume stored procedure. Here I am adding client in same solution of service, by right clicking and adding new project then selecting console application from the Windows tab.

Add reference to the client

sptesting18.gif

Add Service Reference , just click Discover in solution ( if client and service is in same solution else copy paste URL of service there)

sptesting19.gif

Add namespace

using System.Data.Services.Client;
using Client.ServiceReference1;

Here Client is name of the test project.

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Services.Client;
using Client.ServiceReference1;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            DataServiceContext context = new DataServiceContext(new Uri("http://localhost:2989/DataService.svc/"));
            IEnumerable<Emp> empResult = context.Execute<Emp>(new Uri("http://localhost:2989/DataService.svc/GetData"));
            foreach (Emp e in empResult)
            {
                Console.WriteLine(e.EmpName + e.EmpId + e.Dept);

            }

            Console.Read();

        }
    }
}


Output

sptesting20.gif

Conclusion

This article explained about, how to use stored procedure in ADO.NET Data Service.

Future scope

To do inspection of, how to use stored procedure for CUD operation. Till then
Happy Coding

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Dhananjay Kumar
Dhananjay Kumar is a developer who blogs at http://debugmode.net/. He is Microsoft MVP ,Telerik MVP and Mindcracker MVP. You can follow him on twitter  @debug_mode
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Thanks!! by Rodolfo On May 17, 2011
Thanks a lot! the explanation was very good, and was very helpfull for me!
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.