Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
Hi all,

How to call stored procedure in Silverlight Web Application.

I'm working on Silverlight apllication and using WCF services for database connections.

I'm writing queries to retrieve data from database. But I need to retrieve data using stored procedures. How to achieve it?

There is no SQLHelper in Silverlight Application though..

TIA,
Posted
Updated 26-Mar-13 21:21pm
v2

1 solution

C#
<pre>//Well, assuming you use ADO.Net in the service side to access the SQL Server:

//Remember, that SQL Service calls sits in the .Net service application - which is using 
//clean .Net (2.0 -> 4.5) and that, has ADO.Net access. You cannot access ADO.Net 
//directly from the Silverlight side of the application...

//The following code is a method on the service side. It's referred to as a service call. 
//It goes in the .svc file, as a new method.

[OperationContract]
public List<resultingClass>() RunSomeDataFromProcedure()
{
  //Resulting class is the class / type you want to return over the service.
  //You must create it - and that is beyond the scope of the question
  List<resultingClass> result = new List<resultingclass>();

  //The normal ADO.Net or SQL Server connection string
  String connectionString = "Your connection string";

  //A connection to the database
  System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
  conn.ConnectionString = connectionString; //Set the connection's connection string

  //A SQL Command object, to execute the command against
  System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
  cmd.Connection = conn;
  cmd.CommandType = System.Data.CommandType.Text;
  cmd.CommandText = "EXECUTE [DBNAME].[dbo].[StoredProcName] Parameters";

  //Execute the command
  System.Data.SqlDataReader dataReader = cmd.ExecuteReader();

  while (dataReader.Read())
  {  
     //Build resulting class / object / model here
     ResultingClass item = new ResultingClass();
     item.Field1 = dataReader["Field1"].ToString();
     ...
     ..
     .
  }

  return result;
}

//Note: I have not done any exception handling, again, beyond the scope of the question

//Now, when you update your service, a new service call method will appear on the 
//client side. You call this, and a list of ResultingClass will be returned, over 
//the WCF Enabled Silverlight web service.
 
Share this answer
 
v3

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900