user2688063
user2688063

Reputation: 313

Dapper and DynamicParameter()

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));
}

Upvotes: 1

Views: 1043

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064204

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);
}

Upvotes: 1

Related Questions