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

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 == 0)
                {
                    context.Set(entity.GetType()).Add(entity);
                }
                else
                {
                    context.Entry(entity).State = System.Data.EntityState.Modified;
                }
                result = true;
                context.SaveChanges();
            }
            return result; 
        }
原文地址:https://www.cnblogs.com/zyip/p/3535376.html