Search code examples
c#sql-serverentity-frameworkentity-framework-6.1

DbMigration.AlterstoredProcedure (Entity Framework migration): How to represent type smallmoney?


In Entity Framework 6.1, in a C# code-based migration (using System.Data.Entity.Migrations.DbMigration), when altering a stored procedure definition using the DbMigration.AlterStoredProcedure method, what's the proper syntax for adding or modifying a stored procedure parameter of the smallmoney type (on SQL Server 2012)?

For example, if I have a migration method that modifies an existing SQL Server stored procedure which takes three parameters, of type int, varchar, and smallmoney respectively:

public partial class MyCustomMigration : DbMigration
{
    public override void Up()
    {
        this.AlterStoredProcedure("dbo.EditItem", c => new
        {
            ItemID = c.Int(),
            ItemName = c.String(),
            ItemCost = /* What goes here to represent the smallmoney SQL Server type? */
        },
        @" (New sproc body SQL goes here) ");
    }

    // ...
}

Solution

  • Thanks, nemesv, for the hint in your comment! What I was missing is that the types being specified while setting up the stored procedure parameters, i.e. "Int" and "String" in:

    c => new
        {
            ItemID = c.Int(),
            ItemName = c.String(),
            //...
        }
    

    ...are actually methods, and each of those methods -- on class System.Data.Entity.Migrations.Builders.ParameterBuilder -- has a set of optional parameters which affect the SQL generated from the migration script.

    In the case of a smallmoney-type stored procedure argument, I ended up using:

        ItemCost = c.Decimal(precision: 10, scale: 4, storeType: "smallmoney")
    

    The values of precision: 10 and scale: 4 are from the MSDN article money and smallmoney (Transact-SQL), which specifies that smallmoney has precision (total # of digits) of 10 and scale (# of digits to the right of the decimal point) of 4 (for SQL Server 2008 and higher).

    So my complete migration code was:

    public override void Up()
    {
        this.AlterStoredProcedure("dbo.EditItem", c => new
        {
            ItemID = c.Int(),
            ItemName = c.String(),
            ItemCost = c.Decimal(precision: 10, scale: 4, storeType: "smallmoney")
        },
        @" (New sproc body SQL goes here) ");
    }
    

    Which produced the SQL:

    ALTER PROCEDURE [dbo].[EditItem]
        @ItemID [int],
        @ItemName [nvarchar](max),
        @ItemCost [smallmoney]
    AS
    BEGIN
        (New sproc body SQL goes here)
    END