I have this class:
public class Parameters
{
public string UserId {get;set;}
public string OrgId {get;set;}
public string Roles {get;set;}
}
It gets deserialised from a JSON string. So some of the properties are null.
What are the best ways to build up the params list to pass to Dapper.
At the moment my logic for building up the params string to tag on the end of the SQL statement goes like this :
var parameters = string.Empty;
var parametersObj = new { };
if (query.Parameters != null)
{
if (!string.IsNullOrWhiteSpace(query.Parameters.UserId))
{
parameters = string.Format("{0} UserId = @UserId", parameters);
// parametersObj.UserId =
}
if (!string.IsNullOrWhiteSpace(query.Parameters.OrganisationIdentifier))
{
parameters = string.Format("{0}, OrganisationIdentifier = @OrganisationIdentifier", parameters);
}
if (!string.IsNullOrWhiteSpace(query.Parameters.Roles))
{
parameters = string.Format("{0}, Roles = @Roles", parameters);
}
}
var sqlString = string.Format("exec {0} {1}", query.DbObjectName, parameters);
conn.QueryAsync<dynamic>(sqlString, )
As you can see with the parametersObj I was going with the JavaScript way of dynamically building an object. If I did do this with dynamic instead of an object - will it still work?
example:
var parameters = string.Empty;
dynamic parametersObj = new { };
if (query.Parameters != null)
{
if (!string.IsNullOrWhiteSpace(query.Parameters.UserId))
{
parameters = string.Format("{0} UserId = @UserId", parameters);
parametersObj.UserId = query.Parameters.UserId;
}
if (!string.IsNullOrWhiteSpace(query.Parameters.OrganisationIdentifier))
{
parameters = string.Format("{0} OrganisationIdentifier = @OrganisationIdentifier ", parameters);
parametersObj.OrganisationIdentifier= query.Parameters.OrganisationIdentifier;
}
if (!string.IsNullOrWhiteSpace(query.Parameters.Roles))
{
parameters = string.Format("{0} Roles = @Roles", parameters);
parametersObj.Roles= query.Parameters.Roles;
}
}
var sqlString = string.Format("exec {0} {1}", query.DbObjectName, parameters);
conn.QueryAsync<dynamic>(sqlString, parametersObj);
I think the second example will work when you change
dynamic parametersObj = new {};
to
dynamic parametersObj = new ExpandoObject();
and the query to
conn.QueryAsync(sqlString, new
{
UserId = parametersObj.UserId,
...
};
NOTE: filling in the dynamic object like
conn.QueryAsync(sqlString, parametersObj);
will raise the error
Extension methods cannot be dynamically dispatched
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