Solved

invoking a sql server stored proc from mvc controller

Posted on 2013-12-23
7
430 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:hougie40
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

771 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now