Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
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:
Technologies: .NET 3.0 and 3.5, Visual Studio 2008,Visual C# .NET
Total downloads : 90
Total page views :  4393
Rating :
 0/5
This article has been rated :  0 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
StoredProcedureTesting.zip
 
Become a Sponsor


Related EbooksTop Videos


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


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Dhananjay Kumar
I am Dhananjay Kumar. I passed computer science  & engineering from AEC Agra in year 2007. I born and brought up in Jamshedpur , Jharkhand. 
 
I am MCTS on WCF, MOSS Development , .Net Framework 2.0 Web Application so far. I read and write on WCF, SilverLight , SharePoint , ASP.Net MVC, ASP.Net 3.5 Extensions , .Net 4.0 , C# 3.0 , C# 4.0 etc etc.
 
Currently , I am working for UST Global as Software Engineer and active member of Microsoft COE team 
 
I love to read books. I have collection of more than 200 books. I am never married and leaving alone in Trivendrum India.
 
Follow me @
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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
StoredProcedureTesting.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved