.net entity framework 泛型 更新與增加記錄

zyip發表於2014-01-28

 

 

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; 
        }

 

 

相關文章