How to return values to Web API Controller from a

2019-09-06 14:46发布

问题:

I am trying validate values to be inserted into SQL from Web API 2 and Repository Pattern. The database has a stored procedure for checking the values passed (foreign key dependencies etc). The stored proc returns a -1 for each value that is invalid or else isValid=true. I need to pass the param that is invalid to my repository/controller so i can return an http response message to the end user indicating what was invalid. Here's what I have so far in my DBContext. How can I do this?

public void Api_Event_Prefs_InsertUpdateCheck(int individualID, int eventID) {

        var p_PrefID = new SqlParameter() { ParameterName = "@PrefID", Value = System.Data.SqlTypes.SqlInt32.Null, Direction = ParameterDirection.InputOutput };
        var p_individualID = new SqlParameter() { ParameterName = "@IndividualID", Value = individualID, Direction = ParameterDirection.InputOutput };
        var p_eventID = new SqlParameter() { ParameterName = "@eventID", Value = eventID, Direction = ParameterDirection.InputOutput };
        var p_IsValid = new SqlParameter() { ParameterName = "@IsValid", Value = System.Data.SqlTypes.SqlBoolean.False, Direction = ParameterDirection.Output };

        this.Database.ExecuteSqlCommand("Exec dbo.Api_Event_Prefs_InsertUpdateCheck @PrefID, @IndividualID OUT, @EventID OUT, @IsValid OUT", p_PrefID, p_individualID, p_eventID, p_IsValid);

    }

回答1:

You need to use Database.SqlQuery, which lets you execute an stored procedure, or any other query, and get the results of the execution.

ExecuteSqlCommand is only useful for running queries from which don't need to return the data (for example updates or DDL sentences).