简体   繁体   中英

EF5 collecting data from stored procedure that returns a list or nothing

I have a stored procedure that looks like this:

CREATE PROCEDURE [dbo].[Foo]
(
  @ID INT,
  @PARAM1 NVARCHAR(10),
  @Error INT OUT
)
AS 
BEGIN
  IF (@ID < 0)
  BEGIN
    SET @Error = 1
    RETURN
  END

  IF (@ID > 100)
  BEGIN
    SET @Error = 2
    RETURN
  END

  SELECT Field1, Field2, Field3 FROM TABLE WHERE Param = @PARAM1
END

In EF5, I'm calling it like this

ObjectParameter error = new ObjectParameter("Error", typeof(global::System.Int32));
List<MyFoo> list = db.Foo(id, param1, error).ToList();

The code does not compile because "NOT ALL PATH RETURNS A VALUE" which makes sense since I have a couple of "RETURN" calls in the stored procedure.

QUESTION:
What's the right way to call this stored procedure from EF5 (cannot change the stored procedure)?

Thanks in advance

Remove the Error parameter and RETURN s from the SP and use RAISERROR to signal errors. Make sure that severity is greater than 10 so it would throw an SqlException, but less than 17 so it's not a system problem which is reported to DB admin:

CREATE PROCEDURE [dbo].[Foo]
(
  @ID INT,
  @PARAM1 NVARCHAR(10)
)
AS 
BEGIN
  IF (@ID < 0)
  BEGIN
    RAISERROR('ID is less than 0', 16, 0); 
  END

  IF (@ID > 100)
  BEGIN
    RAISERROR('ID is greater than 100', 16, 0); 
  END

  SELECT Field1, Field2, Field3 FROM TABLE WHERE Param = @PARAM1
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM