Search code examples
sql-serverapimodel-view-controllerprocedure

Calling function in API retrieves Failed to load resource: the server responded with a status of 500 ()


I'm working on a code with a stored procedure in mvc framework. I have a field WorkOverDate to pick a date and save it in Unit table. After it is saved I'm looking to add that date into another table called WorkOver. The problem comes when I try to call the function with the stored procedure in the api that updated the info in the Unit and I get this: Failed to load resource: the server responded with a status of 500 () I'm not sure what to do here. Everything I modify in the page, saves correctly, but the stored procedure doesn't work. Any suggestion is highly appreciated.

I have a UnitRepository file which has the following code:

public void UpdateWorkOver()
        {

            using (var cmd = _db.Database.GetDbConnection().CreateCommand())
            {

                cmd.CommandText = "dbo.WorkOverAddDate";
                cmd.CommandType = System.Data.CommandType.StoredProcedure;


                bool isOpen = cmd.Connection.State == ConnectionState.Open;
                if (!isOpen)
                {
                    cmd.Connection.Open();
                }

                cmd.ExecuteNonQuery();


                if (!isOpen)
                {
                    cmd.Connection.Close();
                }
            }

        }

The stored procedure for this is:

CREATE PROCEDURE [dbo].[WorkOverAddDate]

AS

INSERT INTO dbo.WorkOver 
           (UnitID, WODate, CreatedBy, Created) 

SELECT UnitID, WODate, CreatedBy, Created

FROM dbo.WorkOver

UNION

SELECT  ID, WorkOverDate, UpdatedBy, Updated

FROM dbo.Unit

Also, I have an API where I'm calling the function with the Stored Procedure when saving the page.

//Edit

                    unit.Updated = DateTime.Now;
                    unit.UpdatedBy = _securityHelper.CurrentUserID.ToString();
                    _auditHelper.After = unit;

                    _repoUnit.Edit(unit);
                    if (unit.WorkOverDate != null)
                    { ((UnitRepository)_repoUnit).UpdateWorkOver(); }

Solution

  • The problem was that I had to add in the stored procedure :

    Where WorkOverDate IS NOT NULL 
    

    as a null parameter cannot be added to a column that is not nullable. Now it's working.