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

 

 

posted @ 2014-01-28 09:43  zyip  阅读(302)  评论(0编辑  收藏  举报