动态把json对象的字段值赋给某个对象的字段
var dt=Utils.JsonDataTableConvert.ToDataTable(tableJson); foreach (DataRow row in dt.Rows) { var idNO = row["身份证号"]+""; var dbItem = dc.Set<User>().FirstOrDefault(ee=>ee.身份证号==idNO) as dynamic; if (dbItem==null) {//insert dbItem = new User(); foreach (var key in keys) { var val = row[item.Value[key]] + ""; //从json对象中取出 字段的值 //dbItem.UUId=val; //无意义,必须知道字段名UUId
//dbItem[key] = val; //把值赋给数据库查出的对象 会报错:无法将带 [] 的索引应用于“xx”类型的表达式,使用反射解决
MappingValue(dbItem,key,val); } } else {//update foreach (var key in keys) { var val =row[item.Value[key]] + ""; //dbItem[key] = val;无法将带 [] 的索引应用于“Tools.AA”类型的表达式
MappingValue(dbItem,key,val); } } dc.SaveChanges(); }
void MappingValue(User item, string _field, string value) { try { var type = item.GetType(); var field = type.GetProperty(_field); field.SetValue(item, value); } catch (Exception ex) { } }
08D12352-4044-490D-B3FD-978257103C13 From:http://www.cnblogs.com/xuejianxiyang/p/7678079.html