EF5.0区别于EF4.0的crud区别

        public T AddEntity(T entity)
         {
             //EF4.0的写法   添加实体
            //db.CreateObjectSet<T>().AddObject(entity);
            //EF5.0的写法
             db.Entry<T>(entity).State = EntityState.Added;

             //下面的写法统一
             db.SaveChanges();
             return entity;
         }
 
         //实现对数据库的修改功能

         public bool UpdateEntity(T entity)
         {
             //EF4.0的写法
             //db.CreateObjectSet<T>().Addach(entity);
            //db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
             //EF5.0的写法
             db.Set<T>().Attach(entity);
           db.Entry<T>(entity).State = EntityState.Modified;
            return db.SaveChanges() > 0;
       }
 
 

         //实现对数据库的删除功能
         public bool DeleteEntity(T entity)
         {
             //EF4.0的写法
             //db.CreateObjectSet<T>().Addach(entity);
             //db.ObjectStateManager.ChangeObjectState(entity, EntityState.Deleted);
             //EF5.0的写法
            db.Set<T>().Attach(entity);
             db.Entry<T>(entity).State = EntityState.Deleted;
             return db.SaveChanges() > 0;
        }

  

        //实现对数据库的查询  --简单查询
         public IQueryable<T> LoadEntities(Func<T, bool> whereLambda)
         {
             //EF4.0的写法
             //return db.CreateObjectSet<T>().Where<T>(whereLambda).AsQueryable();
             //EF5.0的写法
             return db.Set<T>().Where<T>(whereLambda).AsQueryable();
        }

  

原文地址:https://www.cnblogs.com/ingstyle/p/6655953.html