Solved

invoking a sql server stored proc from mvc controller

Posted on 2013-12-23
7
441 Views
Last Modified: 2013-12-23
Im wishing to call a stored procedure from my delete controller but am not sure how.
This app does use entity framework so im not sure how that comes into play.



My controller code is simply this:

 public ActionResult Delete(int id)
        {
            
       

      //         return to view;        
        }

Open in new window


I want to be able to invoke the sproc from the controller method above.

The sproc returns @@rowcount because I was told that you have to return a value for entity framework to find it in context.  

Any help is appreciated.
0
Comment
Question by:hougie40
  • 4
  • 2
7 Comments
 
LVL 15

Accepted Solution

by:
unknown_routine earned 400 total points
ID: 39736378
You need something similar to below:

SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();


cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;

sqlConnection1.Open();

//Return number of rows
cmd.ExecuteNonQuery() = cmd.ExecuteReader();
0
 
LVL 13

Expert Comment

by:Ashok
ID: 39736681
Here is an example of calling SP:

using (Entities context = new Entities())
{
  string ConnectionString = (context.Connection as EntityConnection).StoreConnection.ConnectionString;
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
    builder.ConnectTimeout = 2500;
    SqlConnection con = new SqlConnection(builder.ConnectionString);
    System.Data.Common.DbDataReader sqlReader;
    con.Open();
    using (SqlCommand cmd = con.CreateCommand())
    {
        cmd.CommandText = "GetEmployeeData";
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        cmd.CommandTimeout = 0;

      sqlReader = (System.Data.Common.DbDataReader)cmd.ExecuteReader();
      IEnumerable<EmployeeDetail> empDetails = context.Translate<EmployeeDetail>(sqlReader).ToList();
    }
}


HTH
Ashok
0
 
LVL 13

Expert Comment

by:Ashok
ID: 39736690
What is the name of your edmx (entity) class?

What is the name of your Stored Procedure?

What (and how many) input parameters does your Stored Procedure have?
0
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 

Author Comment

by:hougie40
ID: 39736724
In the sproc its just going to be a series of delete statements and its just going to take an id and return the rowcount.  The first example that unknown_routine left does work fine.  I am not sure if I need to wire it up to Entity Framework edmx or not but when I try the delete it works because when I retun back to the View the record is gone and is gone from sql server also.

     public ActionResult Delete(int id)
        {
          

                SqlConnection sqlConnection1 = new SqlConnection("server=blahblah");
                SqlCommand cmd = new SqlCommand();


                cmd.CommandText = "exec dbo.spDeleteVehicleAccidentByAccidentId " + "@AccidentId = " + id.ToString();
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Connection = sqlConnection1;

                sqlConnection1.Open();
                try
                {
                //Return number of rows
                cmd.ExecuteNonQuery();

                AddFeedbackMessage("The record has been deleted.");

            }
            catch (Exception ex) {
             Logging.LogError(ex);
            }

            return RedirectToAction("Search");
        }

Open in new window


Here is the sproc.  

ALTER PROCEDURE [dbo].[spDeleteVehicleAccidentByAccidentId]
	-- Add the parameters for the stored procedure here
	@AccidentId int


AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	

--BEGIN TRY
      --BEGIN TRANSACTION
     
	 --Accident Citation
	  DELETE Accident.tbAccidentCitation
      FROM Accident.tbAccidentCitation AS AC
      INNER JOIN Accident.tbAccidentDriver AS AD
            ON AC.DriverId = AD.Id
      WHERE AD.AccidentID = @AccidentID;

      --Accident Driver
	  DELETE Accident.tbAccidentDriver
      WHERE AccidentID = @AccidentID;

	  --other vehicle driver
      DELETE Accident.tbAccidentOtherVehicleDriver
      FROM Accident.tbAccidentOtherVehicleDriver AS OVD
      INNER JOIN Accident.tbAccidentOtherVehicle AS OV
            ON OVD.OtherVehicleId = OV.Id
      WHERE OV.AccidentID = @AccidentID;

	  --other vehicle owner
	   DELETE Accident.tbAccidentOtherVehicleOwner
      FROM Accident.tbAccidentOtherVehicleOwner AS OVO
      INNER JOIN Accident.tbAccidentOtherVehicle AS OV
            ON OVO.OtherVehicleId = OV.Id
      WHERE OV.AccidentID = @AccidentID;

	  --other vehicle insurance
	   DELETE Accident.tbAccidentOtherVehicleInsurance
      FROM Accident.tbAccidentOtherVehicleInsurance AS OVI
      INNER JOIN Accident.tbAccidentOtherVehicle AS OV
            ON OVI.OtherVehicleId = OV.Id
      WHERE OV.AccidentID = @AccidentID;

	   --other vehicle passenger
	   DELETE Accident.tbAccidentOtherVehiclePassenger
      FROM Accident.tbAccidentOtherVehiclePassenger AS OVP
      INNER JOIN Accident.tbAccidentOtherVehicle AS OV
            ON OVP.OtherVehicleId = OV.Id
      WHERE OV.AccidentID = @AccidentID;


	  --Adjuster Participant
      DELETE Accident.tbAccidentAdjuster
      From Accident.tbAccidentAdjuster as AA
	  Inner Join Accident.tbAccidentParticipant as AP
	  ON AP.Id = AA.AdjusterParticipantId
	  WHERE AP.AccidentID = @AccidentID;

	   --Accident Police
      DELETE Accident.tbAccidentPoliceInformation
      From Accident.tbAccidentPoliceInformation as API
	  Inner Join Accident.tbAccidentParticipant as AP
	  ON AP.Id = API.AuthorityParticipantId
	  WHERE AP.AccidentID = @AccidentID;

      DELETE Accident.tbAccidentUnit
      WHERE AccidentID = @AccidentID;

      DELETE Accident.tbAccidentTrailer
      WHERE AccidentID = @AccidentID;

      DELETE Accident.tbAccidentClaimant
      FROM Accident.tbAccidentClaimant AS AC
      INNER JOIN Accident.tbAccidentParticipant AS AP
            ON AC.ClaimantParticipantID = AP.ID  
      WHERE AP.AccidentID = @AccidentID;

      DELETE Accident.tbAccidentParticipant
      WHERE AccidentID = @AccidentID;

      DELETE Accident.tbAccidentOrderStop
      WHERE AccidentID = @AccidentID;

      DELETE Accident.tbAccidentPoliceInformation
      WHERE AccidentID = @AccidentID;
	  
	  DELETE Accident.tbAccidentAnalysis
      WHERE AccidentID = @AccidentID;

	    
	  DELETE Accident.tbAccidentCost
      WHERE AccidentID = @AccidentID;

	  DELETE Accident.tbAccidentContributingFactor
      WHERE AccidentID = @AccidentID;

	  DELETE Accident.tbAccidentDiary
      WHERE AccidentID = @AccidentID;

	  --Finally delete the accident record master
	  DELETE Accident.tbAccident
	  Where Id = @AccidentId

	  select @@ROWCOUNT

Open in new window

0
 
LVL 13

Expert Comment

by:Ashok
ID: 39736764
You are using new database connection (not existing database connection).

Also, you are forgetting to close the connection.
0
 
LVL 13

Assisted Solution

by:Ashok
Ashok earned 100 total points
ID: 39736774
sqlConnection1.Open();
                try
                {
                //Return number of rows
                int i = cmd.ExecuteNonQuery();
sqlConnection1.Close();
                AddFeedbackMessage("The record has been deleted.");
            }
            catch (Exception ex) {
             Logging.LogError(ex);
            }
0
 

Author Closing Comment

by:hougie40
ID: 39736815
It doesnt appear I will need to hook into the edmx to pull this off.  That is subject to change but for now im going with a simpler solution involving a direct connection to sql server.  Thank you both.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question