Entity FrameWork实现增、删、改、分页的数据层代码实现

public bool AddEntity(Customer entity)//添加实体
  {
      MyHotelModelContainer hotelDB = new MyHotelModelContainer();//定义上下文实体
      if (entity.Id == Guid.Empty)
      {
          entity.Id = Guid.NewGuid();
      }
      hotelDB.Customer.AddObject(entity);//调用添加实体方法
      int count = hotelDB.SaveChanges();
      if (count > 0)
      {
          return true;
      }
      return false;
  }
 
  public bool UpdateEntity(Customer entity)//更新实体
  {
      bool result = false;
      MyHotelModelContainer hotelDB = new MyHotelModelContainer();
      hotelDB.Customer.Attach(entity);
      hotelDB.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified);//调用更新实体发法
      int count = hotelDB.SaveChanges();
      if (count > 0)
      {
          result = true;
      }
      return result;
   
  }
 
  public bool DeleteEntity(Guid Id)//根具指定id删除一个实体
  {
      bool result = false;
      MyHotelModelContainer hoteDB = new MyHotelModelContainer();
      //根据id查询出要删除的实体
      var tempDelete = hoteDB.Customer.Where<Customer>(c => c.Id == Id).FirstOrDefault<Customer>();<span style="white-space:pre">    </span>
      if (tempDelete != null)//删除之前的判断
      {
          hoteDB.Customer.DeleteObject(tempDelete);//调用删除实体方法
          var count = hoteDB.SaveChanges();
          if (count > 0)
          result = true;
      }
      return result;
  }
 
  public IQueryable<Customer> GetByWhere(Func<Customer, bool> whereLambda)//根据某种条件等到实体集合  <span style="font-size:12px; font-family:Arial,Helvetica,sans-serif">IQueryable集合可以实现延迟加载功能</span>
  {<span style="white-space:pre">   </span>
      MyHotelModelContainer hoteDB = new MyHotelModelContainer();
      var temp = hoteDB.Customer.Where<Customer>(whereLambda).AsQueryable<Customer>();
      return temp;
  }
 
  public IQueryable<Customer> GetPageEntity(Func<Customer, bool> whereLambda, int? pageSize, int? pageIndex)//实现分页的方法
  {
      MyHotelModelContainer hotelDB = new MyHotelModelContainer();
      var temp = hotelDB.Customer
          .Where<Customer>(whereLambda)
          .OrderBy(c => c.FirstName)
          .Skip<Customer>(pageSize.Value * (pageIndex.Value - 1))
          .Take<Customer>(pageSize.Value)
          .AsQueryable<Customer>();
      return temp;
  }
 
 
  public long GetCount(Func<Customer, bool> whereLambda)//得到中共多少条数据
  {
      MyHotelModelContainer hotelDB = new MyHotelModelContainer();
      return hotelDB.Customer.Where<Customer>(whereLambda).Count();
  }
posted @ 2014-04-22 11:47  armyfai  阅读(321)  评论(0编辑  收藏  举报