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
You don't need to do anything: just pass your object as the parameters . Dapper will only pass in properties/parameters that it can identify in the query... and even if it passed them all in: it understands null.
The object is fine.
...QueryAsync(sql, query.Parameters)...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.