.net entity framework 泛型 更新与增加记录

时间:2022-02-10 00:25:17
static public bool SaveOrUpdate<T>(T entity) where T: class
{
bool result = false;
using (wechatEntities context = new wechatEntities())
{
Type t = entity.GetType();
PropertyInfo[] properts = t.GetProperties();
PropertyInfo p = t.GetProperty("Id");
if (p == null)
p = t.GetProperty("id");
if (p == null)
p = t.GetProperty("ID");
if (p == null)
{
return result;
}
var id = Convert.ToInt32(p.GetValue(entity,null)); if (id == )
{
context.Set(entity.GetType()).Add(entity);
}
else
{
context.Entry(entity).State = System.Data.EntityState.Modified;
}
result = true;
context.SaveChanges();
}
return result;
}