Avatar of Steve Hougom
Steve Hougom
Flag for United States of America asked on

invoking a sql server stored proc from mvc controller

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.
C#ASP.NET

Avatar of undefined
Last Comment
Steve Hougom

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
unknown_routine

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Ashok

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
Ashok

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?
Steve Hougom

ASKER
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

Your help has saved me hundreds of hours of internet surfing.
fblack61
Ashok

You are using new database connection (not existing database connection).

Also, you are forgetting to close the connection.
SOLUTION
Ashok

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Steve Hougom

ASKER
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.