Dapper and DynamicParameter()

dapper

Question

I am looking through the code and I am unable to read it. I also tried to find material and examples but I was unable to find specific or any documentation that could help me understand the issue. Can someone read me the code and if there is any documentation to read it.

At first my question is why do we need to use DynamicParameter() which is an object of Dapper. I am also not sure what does => means.

public void validRecord(string fileName, string rawContent, int userId)
{
    Run(conn => conn.Execute("[dbo].[storedProc_GETDone]"
        , new DynamicParameters
            (new Dictionary<string, object>
                {
                    {"fileName", fileName},
                    {"rowContent", rawContent},
                    {"userCreated", userId},
                }), CommandType.StoredProcedure));
}

Expert Answer

Run is not part of dapper, but => in C# is used to create a lambda expression, in this case I expect it is an Action<DbConnection>, i.e. I would guess that your run looks a lot like this:

Run(Action<DbConnection> action) {
    using(var conn = CreateConnection()) {
        conn.Open();
        action(conn);
    }
}

i.e. it is "I'm going to give you a connection; what do you want to do with it?" - in this case you are choosing to Execute a stored procedure.

Now, it is worth noting that in your example there is no benefit in using DynamicParameters, since the information is well known - you could just use:

Run(conn => conn.Execute("[dbo].[storedProc_GETDone]",
    new { fileName, rawContent, userCreated = userId },
    CommandType.StoredProcedure));

which would work just as well. So in answer to "why do we need to use DynamicParameter - you don't in this scenario. However, in some cases you might - especially if you are building SQL on the fly manually, for example:

if(name != null) {
    sql.Append("and Name = @name ");
    args.Add("name", name);
}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why