I have some function whose prototype looks kind of like this:
public void doThings(string sql, dynamic dParams);
It does some kind of SQL querying with those parameters. I didn't write it but I have to use it. It works fine when I do something like this:
doThings("select * from SomeTable where myval1=@v1 and myval2=@v2",
new
{
v1 = new Dapper.DbString()
{
Value = "yay",
IsAnsi = true,
Length = 50
},
v2 = new Dapper.DbString()
{
Value = "really",
IsAnsi = true,
Length = 32
}
});
But not when I first put the dynamic params into an ExpandoObject:
dynamic dynParams = new ExpandoObject();
dynParams.v1 = new Dapper.DbString()
{
Value = "yay",
IsAnsi = true,
Length = 50
}
doThings("query here", dynParams);
The query then returns no results. I don't want to call doThings()
and write that new
block ten times for ten different scenarios where I might want to query for myval2
or myval3
and so on. Is there some special way I should be passing the ExpandoObject
, or some other way I should be doing this in general?
The ExpandoObject class is an implementation of the dynamic object concept that enables getting, setting, and invoking members.
Use ExpandoObject to create an object that you can add properties, methods, and events to and be able to data bind to in a user interface. ExpandoObject allows you to write code that is more readable than typical reflection code with GetProperty(“Field”) syntax.
For ExpandoObject, you can simply check whether the property is defined as a key in the underlying dictionary. For other implementations, it might be challenging and sometimes the only way is to work with exceptions.
Dapper doesn't support Expandos by default, but you can pass the expando to the constructor of a Dictionary<string,object>
and then pass that as the dynamic argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With