我正在尝试使用动态参数和dapper来获取数据。
public User GetSingle(dynamic param)
{
string query = string.Format(@"SELECT * FROM Users WHERE ");
if (param == null)
throw new Exception("Dynamic parameter can not be null.");
string whereClause = GetWhereQuery(param);
User item = null;
using (var connection = ConnectionManager.GetConnection())
{
connection.Open();
item = connection.Query<User>(query + whereClause , (object) param).FirstOrDefault();
}
return item;
}
GetWhereQuery的代码是:
private string GetWhereQuery(dynamic item)
{
PropertyInfo[] props = item.GetType().GetProperties();
string[] columns = props.Select(p => p.Name).ToArray();
var builder = new StringBuilder();
for (int i = 0; i < columns.Count(); i++)
{
string col = columns[i];
builder.Append(col);
// This is required for working with this database.
builder.Append("=:");
builder.Append(col);
if (i < columns.Count() - 1)
{
builder.Append(" AND ");
}
}
return builder.ToString();
}
该代码适用于单个参数,例如new {ID = 1}。 但是,当我使用多个参数,如new {Name =“ABC”,Age =“19”}时,它从数据库中取不出任何内容。在这种情况下,数据存在于数据库中,用于这些参数。