user1790300 user1790300 - 1 month ago 15
ASP.NET (C#) Question

How to limit parameters passed using Dapper's DynamicParameter constructor

Using the Dapper DynamicParameters constructor, is there a way to exclude certain parameters from being included. For example, say I have the following entity,

public class EntityA
{
public string Method1 { get; set; }
public string Method2 { get; set; }
public string Method3 { get; set; }
}


and I am calling a stored procedure that only has Method1 and Method2 as parameters, can I have the DynamicParameters method only pass the those two parameters and skip the third parameter? For my live example, I have alot more properties for my entity and would rather use an exclude scenario than specify parameter by hand.

Answer

The simplest option here is an anonymous projection - this can be done for either the argument object itself, or to the parameter to DynamicParameters if you need to add additional custom parameters; for example:

conn.Execute(sql, new { obj.Foo, obj.Bar });

or:

var args = new DynamicParameters(new { obj.Foo, obj.Bar });
// not shown: add some more custom parameters
conn.Execute(sql, args);
Comments