一、单条数据转换成对象的工具类
/// <summary>
/// 将单条数据转换成对象
/// 2021年12月6日11:04:18
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static T SingleConvertToModel(DataTable dt)
{
T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
if (dt.Columns.Contains(pi.Name))
{
if (!pi.CanWrite) continue;
var value = dt.Rows[0][pi.Name];
if (value != DBNull.Value)
{
switch (pi.PropertyType.FullName)
{
case "System.Decimal":
pi.SetValue(t, decimal.Parse(value.ToString()), null);
break;
case "System.String":
pi.SetValue(t, value.ToString(), null);
break;
case "System.Int32":
pi.SetValue(t, int.Parse(value.ToString()), null);
break;
default:
pi.SetValue(t, value, null);
break;
}
}
}
}
return t;
}
二、调用并转换成json
DataTable data = DataAccess.Access().GetTableByProcedure("存储名称",
new SqlParameter[]{
new SqlParameter("@入参",入参 ),
});
PatientInfo patientInfo = new PatientInfo(jsonStr);
patientInfo = ToModel<PatientInfo>.SingleConvertToModel(data);
String json = JsonConvert.SerializeObject(patientInfo);