首页 > 代码库 > EF增删改查+使用Expression进行排序分页

EF增删改查+使用Expression进行排序分页

注:以下部分来自《ASP.NET MVC 企业级实战》一书的摘抄和改写以及部分个人学习心得。

EF简单增删改查

  1. 增加  
 public static int Add()
        {
            using (NorthwindEntities db=new NorthwindEntities())
            {
                Customers cs2 = new Customers
                {
                    CustomerID = "11",
                    ContactName="aa4444sa",
                    Address="上海杨浦",
                    City= "上海",
                    CompanyName="XX公司"
                    
                };
                //第一种方法
                //db.Customers.Add(cs2);
                //第二种方法 将对象加入EF容器,并获取当前实体对象的状态管理对象
                DbEntityEntry<Customers> entry = db.Entry<Customers>(cs2);
                entry.State = System.Data.Entity.EntityState.Added;
                try
                {
                     db.SaveChanges();
                }
                catch (Exception e)
                {
                }
                return 1;
            }               
        }

 

  1. 查询

 

 public static void QueryDealy()
        {
            using (NorthwindEntities db=new NorthwindEntities())
            {
         //延迟加载,此处返回的其实是一个DBquery对象 IQueryable
<Orders> or = db.Orders.Where(u=>u.CustomerID=="11").Take(1);
         //toList(),用到DBquery对象即时执行语句从数据库查询数据 List
<Orders> aa = or.ToList(); } }

 

  1. 修改
/// <summary>
        /// 官方推荐的 修改方式(先查询,再修改)
        /// </summary>
        static void Edit()
        {
            using (NorthwindEntities db = new NorthwindEntities())
            {
                //1.查询出一个 要修改的对象 -- 注意:此时返回的是一个Customers类的代理类对象(包装类对象)
                Customers _Customers = db.Customers.Where(u => u.CustomerID == "zouqj").FirstOrDefault();
                Console.WriteLine("修改前:" + _Customers.ContactName);
                //2.修改内容 -- 注意:此时其实操作的是代理类对象 的属性,这些属性,会将值设置给内部的 Customers对象对应的属性,同时标记此属性为已修改状态
                _Customers.ContactName = "邹玉杰";
                //3.重新保存到数据库 -- 注意:此时 ef上下文,会检查容器内部 所有的对象,找到标记为修改的对象,然后找到标记为修改的对象属性,生成对应的update语句执行!
                db.SaveChanges();
                Console.WriteLine("修改成功:");
                Console.WriteLine(_Customers.ContactName);
            }
        }

直接修改:

/// <summary>
        /// 自己优化的修改方式(创建对象,直接修改)
        /// </summary>
        static void Edit2()
        {
            //1.查询出一个 要修改的对象
            Customers _Customers = new Customers()
            {
                CustomerID = "11",
                Address = "2222222",
                City = "上海",
                Phone = "15243641131",
                CompanyName = "xx有限公司",
                ContactName = "qgc"
            };
            using (NorthwindEntities db = new NorthwindEntities())
            {
                //2.将对象加入EF容器,并获取当前实体对象的状态管理对象
                DbEntityEntry<Customers> entry = db.Entry<Customers>(_Customers);
                //3.设置 该对象 为被修改过
                entry.State = System.Data.EntityState.Unchanged;
                //4.设置该对象的ContactName属性为修改状态,同时 entry.State 被修改为 Modified 状态
                entry.Property("ContactName").IsModified = true;

                //var u = db.Customers.Attach(_Customers);
                //u.ContactName = "郭富城";

                //3.重新保存到数据库 -- ef 上下文会根据 实体对象的 状态 ,根据 entry.State =Modified 的值生成对应的 update sql 语句
         //所以数据只更新ContactName属性,因为上面只设置该对象为修改模式
db.SaveChanges(); Console.WriteLine("修改成功:"); Console.WriteLine(_Customers.ContactName); } }

 

  1. 删除
/// <summary>
        ///  删除
        /// </summary>
        static void Delete()
        {
            using (NorthwindEntities db = new NorthwindEntities())
            {
                //1.创建要删除的 对象
                Customers u = new Customers() { CustomerID = "zouqj" };
                //2.附加到 EF中
                db.Customers.Attach(u);
                //3.标记为删除 注意:此方法就是标记当前对象为删除状态 !
                db.Customers.Remove(u);

                /*
                    也可以使用 Entry 来附加和 修改
                    DbEntityEntry<Customers> entry = db.Entry<Customers>(u);
                    entry.State = System.Data.EntityState.Deleted;
                 */

                //4.执行删除sql
                db.SaveChanges();
                Console.WriteLine("删除成功!");
            }
        }

 

  1. 批量操作
  /// <summary>
        ///  批处理 -- 一次新增 50条数据
        /// </summary>
        static void BatcheAdd()
        {
            using (NorthwindEntities db = new NorthwindEntities())
            {
                for (int i = 0; i < 50; i++)
                {
                    Customers _Customers = new Customers
                    {
                        CustomerID = "01" + i,
                        Address = "上海XX街",
                        City = "上海",
                        Phone = "1314520",
                        CompanyName = "微软",
                        ContactName = "qgc" + i
                    };
                    db.Customers.Add(_Customers);
                }
                db.SaveChanges();
            }
        }
   static void SaveBatched()
        {
            //1新增数据
            Customers _Customers = new Customers
            {
                CustomerID = "222",
                Address = "333",
                City = "444",
                Phone = "1314520",
                CompanyName = "微软",
                ContactName = "qgc"
            };
            using (NorthwindEntities db = new NorthwindEntities())
            {
                db.Customers.Add(_Customers);

                //2新增第二个数据
                Customers _Customers2 = new Customers
                {
                    CustomerID = "zhaokuanying",
                    Address = "洛阳西街",
                    City = "洛阳",
                    Phone = "1314520",
                    CompanyName = "微软",
                    ContactName = "赵匡胤"
                };
                db.Customers.Add(_Customers2);

                //3修改数据
                Customers usr = new Customers() { CustomerID = "zhaomu", ContactName = "赵牧" };
                DbEntityEntry<Customers> entry = db.Entry<Customers>(usr);
                entry.State = System.Data.EntityState.Unchanged;
                entry.Property("ContactName").IsModified = true;

                //4删除数据
                Customers u = new Customers() { CustomerID = "zouyujie" };
                //附加到 EF中
                db.Customers.Attach(u);
                //标记为删除 注意:此方法就是标记当前对象为删除状态 !
                db.Customers.Remove(u);

                db.SaveChanges();
                Console.WriteLine("批处理 完成~~~~~~~~~~~~!");
            }
        }

 

Expression动态查询、分页

Expression,表达式树,以lamda表达式创建,就以表达式目录树的形式将强类型的lambda表达式标识为数据结构。

排序

 /// <summary>
        /// 根据条件排序和查询
        /// </summary>
        /// <typeparam name="TKey">排序字段类型</typeparam>
        /// <param name="whereLambda">查询条件 lambda表达式</param>
        /// <param name="orderLambda">排序条件 lambda表达式</param>
        /// <returns></returns>
        public static  IEnumerable<Customers> GetListBy<TKey>(Expression<Func<Customers, bool>> whereLambda, Expression<Func<Customers, TKey>> orderLambda)
        {
            using (NorthwindEntities db = new NorthwindEntities())
            {
                return db.Customers.Where(whereLambda).OrderBy(orderLambda).ToList();
            }
        }

常见分页

 

 /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="whereLambda">条件 lambda表达式</param>
        /// <param name="orderBy">排序 lambda表达式</param>
        /// <returns></returns>
        public static List<Customers> GetPagedList<TKey>(int pageIndex, int pageSize, Expression<Func<Customers, bool>> whereLambda,
                    Expression<Func<Customers, TKey>> orderBy)
        {
            using (NorthwindEntities db = new NorthwindEntities())
            {
                // 分页时一定注意: Skip 之前一定要 OrderBy
                return db.Customers.Where(whereLambda).OrderBy(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
        }

 

EF增删改查+使用Expression进行排序分页