//刚开始通过EF添加数据都是这样的...↓
var db = new DBEntities()
T_User t_userinfo = new T_User()
{
Type = "type1",
AliasName = "alisaname1",
Description = "description..."
};
db.T_UserGroup.Add(t_userinfo);
db.SaveChanges();
//这个表有几个字段就要需要一个个的赋值...
//如果字段太多代码也会相应增加...开发速度也慢..
//想封装起来直接调用就好了
//封装的方法...
public static TEntity setNewTEntityValue<TEntity>(Dictionary<string, Object> userInfoDic) where TEntity : class
{
var entity = Activator.CreateInstance<TEntity>();
int tempInt = ;
DateTime tempDateTime = DateTime.Now;
foreach (var pro in entity.GetType().GetProperties())
{
//如果传来的参数中有 全部属性中的值,则开始赋值...
//目的主要还是判断传来要更新的有哪些参数...
if (userInfoDic.ContainsKey(pro.Name))
{
switch (pro.PropertyType.Name.ToLower())
{
case "int32":
//pro.SetValue(entity, userInfoDic[pro.Name].ToString());//测试代码...
int.TryParse(userInfoDic[pro.Name].ToString(), out tempInt);
pro.SetValue(entity, tempInt);
break;
case "string":
pro.SetValue(entity, userInfoDic[pro.Name].ToString());
break;
case "datetime":
//tempDateTime = DateTime.ParseExact(key.Value.ToString(), "", System.Globalization.CultureInfo.InvariantCulture);
pro.SetValue(entity, tempDateTime);
break;
default:
pro.SetValue(entity, userInfoDic[pro.Name].ToString());
break;
}
}
}
return entity;
}
//调用方法 Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("Type", "type1");
dic.Add("AliasName", "alisaname1");
dic.Add("Description", "description...");//我这里是添加的测试数据,本来的数据是web端传过来json,我解析出来的就和dic是一样的字典表
T_User info = CommonService.setNewTEntityValue<T_User>(dic);
db.T_UserGroup.Add(info);
db.SaveChanges();
记录点滴...^_^