代码:
//这样写的话,输入的是表的行对象,返回的是数据字典,可以直接用到更新操作里,
public static Object AlterDate(Object tabledataobj)
{
List<string> namelist = new List<string>();
List<Object> valuelist = new List<object>();
Type t = tabledataobj.GetType();
foreach (PropertyInfo pi in t.GetProperties())
{
if (pi.Name == "id")
{ }
else
{
Object value = pi.GetValue(tabledataobj);
if (value != null)
{
namelist.Add(pi.Name);
valuelist.Add(value);
}
}
}
Dictionary<string, object> temp = new Dictionary<string, object>();
for (int i = 0; i < namelist.Count; i++)
{
temp.Add(namelist[i], valuelist[i]);
}
temp.Add("updateTime", DateTime.Now);
return temp;
}
//用到更新操作里,参考如下:
var dic = new Dictionary<string, string>();
dic.Add("name", "第十三条");
dic.Add("areaId", "1");
db.Update<School, int>(dic, 13);
或:
Object obj = AlterTable.AlterDate(dt);
……
var result = db.Update<t_customer,int>(obj,cusid);
//方法重载,只有第二个参数里包含的字段才能进行修改
public static Object AlterDate(Object tabledataobj,List<string> modifiableField)
{
List<string> namelist = new List<string>();
List<Object> valuelist = new List<object>();
Type t = tabledataobj.GetType();
foreach (PropertyInfo pi in t.GetProperties())
{
if (pi.Name == "id")
{ }
else
{
if (modifiableField.Contains(pi.Name))
{
Object value = pi.GetValue(tabledataobj);
if (value != null)
{
namelist.Add(pi.Name);
valuelist.Add(value);
}
}
}
}
Dictionary<string, object> temp = new Dictionary<string, object>();
for (int i = 0; i < namelist.Count; i++)
{
temp.Add(namelist[i], valuelist[i]);
}
temp.Add("updateTime", DateTime.Now);
return temp;
}
//这样写的话,后面表示的是动态的的生成对象,并且动态的给对象添加属性
public static Object AlterDate(Object tabledataobj)
{
List<string> namelist = new List<string>();
List<Object> valuelist = new List<object>();
Type t = tabledataobj.GetType();
foreach (PropertyInfo pi in t.GetProperties())
{
if (pi.Name == "id")
{ }
else
{
Object value = pi.GetValue(tabledataobj);
if (value != null)
{
namelist.Add(pi.Name);
valuelist.Add(value);
}
}
}
Dictionary<string, object> temp = new Dictionary<string, object>();
for (int i = 0; i < namelist.Count; i++)
{
temp.Add(namelist[i], valuelist[i]);
}
temp.Add("updateTime", DateTime.Now);
dynamic result = new System.Dynamic.ExpandoObject();
foreach (KeyValuePair<string, object> item in temp)
{
((IDictionary<string, object>)result).Add(item.Key, item.Value);
}
return result;
}