/// <summary>
/// 获取数据库行实例。
/// </summary>
public static T Query<T>(string sql, params DbParameter[] parameters) where T : new()
{
T result = new T();
DatabaseOperationHelper doh = new DatabaseOperationHelper(Utility.ProviderName,
Utility.ConnectionString);
DataTable table = doh.GetDataTable(sql, CommandType.Text, parameters);
if ((table == null) || (table.Rows.Count == 0)) { return result; }
FillPropertiesInfo(ref result, table.Rows[0]);
return result;
}
/// <summary>
/// 将列名称与属性名称匹配,填充属性值
/// </summary>
private static void FillPropertiesInfo<T>(ref T obj, DataRow row)
{
if (obj == null) { return; }
PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
object value = string.Empty;
foreach (PropertyInfo prop in props)
{
for (int i = 0; i < row.Table.Columns.Count; i++)
{
if (row.Table.Columns[i].ColumnName.Equals(prop.Name, StringComparison.CurrentCultureIgnoreCase))
{
value = row[i];
Type type = prop.PropertyType;
if (type == typeof(string))
{
value = (value != DBNull.Value ? value.ToString() : string.Empty);
}
else if (type == typeof(int))
{
value = (value != DBNull.Value ? Convert.ToInt32(value) : -1);
}
else if (type == typeof(bool))
{
value = (value != DBNull.Value ? Convert.ToBoolean(value) : false);
}
else if (type == typeof(byte[]))
{
value = (value != DBNull.Value ? (value as byte[]) : new byte[0]);
}
else if (type == typeof(DateTime))
{
value = (value != DBNull.Value ? Convert.ToDateTime(value) : DateTime.Now);
}
prop.SetValue(obj, value, null);
}
}
}
}