Can I use DynamicParameters with Template and have a return parameter in dapper?

天涯浪子 提交于 2019-12-05 15:04:42

With a quick tweak, Add now replaces the value from a template, allowing:

public void TestProcWithOutParameter()
{
    connection.Execute(
        @"CREATE PROCEDURE #TestProcWithOutParameter
@ID int output,
@Foo varchar(100),
@Bar int
AS
SET @ID = @Bar + LEN(@Foo)");
    var obj = new
    { // this could be a Person instance etc
        ID = 0,
        Foo = "abc",
        Bar = 4
    };
    var args = new DynamicParameters(obj);
    args.Add("ID", 0, direction: ParameterDirection.Output);
    connection.Execute("#TestProcWithOutParameter", args,
                 commandType: CommandType.StoredProcedure);
    args.Get<int>("ID").IsEqualTo(7);
}

Is that close enough? You can also use ParameterDirection.ReturnValue, of either a pre-existing value or a new value. Note it does not update directly back into the original template; the value must be fetched from the DynamicParameters instance (as shown).

When you use the constructor for DynamicParameters to specify a template object you will still need to specify that @ID is an output parameter. At first, via the template, it will be set to ParameterDirection.Input. Once you add it, it will be overridden to have the updated values, then you can get the value by the parameter name as follows:

procParams.Add("@ID", dbType: DbType.Int32, direction: ParameterDirection.Output);
// ... execute ...
person.ID = procParams.Get<int>("@ID");

I was able to get this working and used your classes and code, in addition to what I showed above.

EDIT: as discussed in the comments, the stored procedure doesn't accept more arguments than it has declared. Thus, an alternate approach is to ditch the stored procedure and resort to some inline SQL. When you use a query Dapper will ignore any parameters given to it that aren't specified in the SQL statement. This is a work-around to tackle this issue:

string sql = "INSERT INTO Person (Name, DOB) VALUES (@Name, @DOB) SELECT SCOPE_IDENTITY()";
decimal id = conn.Query<decimal>(sql, procParams).First();
person.ID = (int)id;

Note that SCOPE_IDENTITY() returns a decimal, not an int.

Another idea, which I think isn't ideal, is to modify the Dapper code and add a Remove method to the DynamicParameters class to remove undesired parameters. This doesn't save you much though since you'll still spend time specifying which parameters to remove all for the sake of making a stored procedure happy. If you decide to implement this remember that case matters when specifying the key to remove from the parameters dictionary.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!