1

In my application (VS2015, C#, WebForm), I had the following code that used to work totally fine before (both locally and on production server) but now I'm getting errors:

Stored procedure to insert an item:

CREATE PROCEDURE [dbo].[StoredProcedure_Item_Insert]
    @ItemText VARCHAR(250),
    @InsertedID INT OUTPUT

    INSERT INTO [dbo].[Item] ([ItemText])
    VALUES (@ItemText  -- ItemText - varchar(250)
           );

    SET @InsertedID = SCOPE_IDENTITY();

    SELECT @InsertedID AS InsertedID;

Repository code:

public int InsertItem(string itemText)
{
        ObjectParameter InsertedId = new ObjectParameter("InsertedID", -1);

        _db.StoredProcedure_Item_insert(feeText, InsertedId);

        return (int)InsertedId.Value;
}

Function import for this stored procedure in the .edmx file

Returns a Collection Of Scalars: Int32

And when I click the Get Column Information button, I get

Name: InsertedID
EDM Type: Int32
Db Type: int
Nullable: true

The only change made I can think of is that my machine was upgraded to Windows 10 so I had to reinstall VS2015.

What I've tried/found:

  • InsertedId.Value is always -1
  • The error message is in 'InsertedId` --> 'MappableType' --> 'DeclaringMethod'
  • The error in DeclaringMethod says

    ((System.RuntimeType)InsertedId.MappableType).DeclaringMethod threw an exception of type System.InvalidOperationException System.Reflection.MethodBase {System.InvalidOperationException}

  • DeclaringMethod.Message says

    Method may only be called on a Type for which Type.IsGenericParameter is true.

  • Tried OUT and OUTPUT in the stored procedure

  • Tried SELECT @InsertedID and RETURN @InsertedID
  • Tried new ObjectParameter("InsertedID", typeof(Int32)) instead of -1 for the second parameter

I've been trying to figure out what is going on for so many hours now but I'm totally stuck...

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
kabichan
  • 1,063
  • 4
  • 19
  • 49
  • [duplicate](https://stackoverflow.com/questions/18469295/retrieve-stored-procedure-output-parameters-in-entity-framework-always-null) – Ali.Asadi Jun 03 '18 at 12:40

1 Answers1

0

I guess it makes sense that it was complaining that the result returned from the stored procedure was a result set, but I still don't know why it used to work... anyhow changing the code as follows did the trick.

Changed from:

    public int InsertItem(string itemText)
        {
            ObjectParameter InsertedId = new ObjectParameter("InsertedID", -1);
            _db.usp_Fee_insert(itemText, InsertedId);
            return (int)InsertedId.Value;
        }

To this:

public int InsertItem(string itemText)
    {
        ObjectParameter InsertedId = new ObjectParameter("InsertedID", -1);
        var result = _db.usp_Fee_insert(itemText, InsertedId);
        return (int)InsertedId.Value;
    }
kabichan
  • 1,063
  • 4
  • 19
  • 49