EF Core基础入门

1. 安装

此处使用的是SQL SERVER数据库,.Net 框架式 .Net Core 2.2,由于.Net core 2.2的Microsoft.AspNetCore.App已经集成了对SQL Server的 EF Core 框架,所以不必再进行安装

2. 实例教程

  1. 增加
  #region 保存
        /// 
        /// 保存
        /// 
        public void Add()
        {
            User userModel = new User()
            {
                CreateTime = DateTime.Now,
                UserGroup = "111111",
                UserName = "小李",
                UserNo = "8440"
            };
            var resultUserModel = _testContext.User.Add(userModel);
            int i = _testContext.SaveChanges();
        }
        #endregion
  #region 异步保存
        /// 
        /// 异步保存
        /// 
        public void AddAsync()
        {

            User userModel = new User()
            {
                CreateTime = DateTime.Now,
                UserGroup = "111111",
                UserName = "小李异步保存的",
                UserNo = "8440"
            };

            var resultUserModel = _testContext.User.Add(userModel);
            var result = _testContext.SaveChangesAsync();
        }
        #endregion
#region 批量增加
        /// 
        /// 批量增加
        /// 
        private void AddBulk()
        {

            List listUsers = new List();
            for (int i = 0; i < 100000; i++)
            {
                Usergroup UsergroupModel = new Usergroup()
                {
                    CreateTime = DateTime.Now,
                    GroupId = "111111" + i.ToString(),
                    GroupName = i.ToString()
                };
                listUsers.Add(UsergroupModel);
            }
            var sw = new Stopwatch();
            sw.Start();
            _testContext.Usergroup.AddRange(listUsers);
            _testContext.SaveChanges();
            sw.Stop();
            var spanTime = sw.Elapsed.TotalSeconds;

            //List listUsers = new List();
            //for (int i = 0; i < 100000; i++)
            //{
            //    User userModel = new User()
            //    {
            //        CreateTime = DateTime.Now,
            //        UserGroup = "111111",
            //        UserName = "小李",
            //        UserNo = i.ToString()
            //    };
            //    listUsers.Add(userModel);
            //}
            //var sw = new Stopwatch();
            //sw.Start();
            //_testContext.User.AddRange(listUsers);
            //_testContext.SaveChanges();
            //sw.Stop();
            //var spanTime = sw.Elapsed.TotalSeconds;

        }

        #endregion
  1. 修改
#region 批量修改指定字段
        /// 
        /// 批量修改指定字段
        /// 
        private void UpdateBulk()
        {

            var modelList = _testContext.User.Where(s => s.UserId > 55002 && s.UserId < 105002).ToList();
            // var modelList = _testContext.User.ToList();
            foreach (var VARIABLE in modelList)
            {
                VARIABLE.UserNo = "2222222";
            }
            var sw = new Stopwatch();
            sw.Start();

            //方法一,自带的UpdateRange
            _testContext.User.UpdateRange(modelList);
            ViewBag.dataCount = _testContext.SaveChanges();
            sw.Stop();
            var spanTime = sw.Elapsed.TotalSeconds;
            ViewBag.spanTime = spanTime;
        }
        #endregion

        #region 修改
        /// 
        /// 修改
        /// 
        public int Update()
        {
            User userModel = new User()
            {
                CreateTime = DateTime.Now,
                UserGroup = "111111",
                UserName = "小李-22222修改的",
                UserNo = "8440",
                UserId = 55002
            };
            var resultUserModel = _testContext.User.Update(userModel);
            int i = _testContext.SaveChanges();
            return i;
        }
        #endregion

        #region 修改指定字段
        /// 
        /// 修改指定字段
        /// 
        public int UpdatePart()
        {
            User userModel = new User()
            {
                CreateTime = DateTime.Now,
                UserGroup = "113434534511",
                UserName = "小李-22222修改的",
                UserNo = "8440",
                UserId = 55002
            };
            _testContext.Attach(userModel);
            _testContext.Entry(userModel).Property(s => s.UserGroup).IsModified = true;
            _testContext.Entry(userModel).Property(s => s.CreateTime).IsModified = false;
            _testContext.Entry(userModel).Property(s => s.UserName).IsModified = false;
            _testContext.Entry(userModel).Property(s => s.UserNo).IsModified = false;
            int i = _testContext.SaveChanges();
            return i;
        }
        #endregion
  1. 删除
#region 异步批量删除
        /// 
        /// 异步批量删除
        /// 
        /// 
        private async Task RemoveBulkAsync()
        {
            var userModel = _testContext.User.Take(1000).ToList();
            var sw = new Stopwatch();
            sw.Start();
            _testContext.User.RemoveRange(userModel);
            ViewBag.dataCount = await _testContext.SaveChangesAsync();
            ViewBag.spanTime = sw.Elapsed.TotalSeconds;
        }
        #endregion

        #region 异步删除
        /// 
        /// 异步删除
        /// 
        /// 
        private async Task RemoveAsync()
        {
            var userModel = _testContext.User.FirstOrDefault();
            var sw = new Stopwatch();
            sw.Start();
            _testContext.User.Remove(userModel);
            ViewBag.dataCount = await _testContext.SaveChangesAsync();
            ViewBag.spanTime = sw.Elapsed.TotalSeconds;
        }
        #endregion

        #region 批量删除
        /// 
        /// 批量删除
        /// 
        private void RemoveBulk()
        {
            var userModel = _testContext.User.Take(1000).ToList();
            var sw = new Stopwatch();
            sw.Start();
            _testContext.User.RemoveRange(userModel);
            ViewBag.dataCount = _testContext.SaveChanges();
            ViewBag.spanTime = sw.Elapsed.TotalSeconds;
        }
        #endregion

        #region 删除
        /// 
        /// 删除
        /// 
        private void Remove()
        {
            var userModel = _testContext.User.FirstOrDefault();
            var sw = new Stopwatch();
            sw.Start();
            _testContext.User.Remove(userModel);
            ViewBag.dataCount = _testContext.SaveChanges();
            ViewBag.spanTime = sw.Elapsed.TotalSeconds;
        }
        #endregion
  1. 各种查询,分页查询等
 /// 
        /// 动态条件分页查询
        /// 
        /// 
        /// 
        /// 
        private object GetModelJoinSearchPage(int page, int pageSize)
        {
            string userName = "小李";
            string groupName = "";
            int userId = 0;
            var sw = new Stopwatch();
            sw.Start();
            var result = (from user in _testContext.User
                          join userGroup in _testContext.Usergroup on user.UserGroup equals userGroup.GroupId into t1
                          from a in t1.DefaultIfEmpty()
                              // where string.IsNullOrEmpty(userName) || user.UserName.Contains(userName)
                              //where string.IsNullOrEmpty(groupName) || a.GroupName.Contains(groupName)
                          where userId != 0 ? user.UserId == userId : true
                          where string.IsNullOrEmpty(userName)?true:user.UserName.Contains(userName)
                          where string.IsNullOrEmpty(groupName) ? true : a.GroupName.Contains(groupName)                          
                          select new
                          {
                              user.UserId,
                              user.CreateTime,
                              user.UserGroup,
                              user.UserNo,
                              user.UserName,
                              a.GroupName
                          }).Skip(page<=1?0:((page - 1) * pageSize)).Take(pageSize).ToList();
            sw.Stop();
            ViewBag.spanTime = sw.Elapsed.TotalSeconds;
            ViewBag.dataCount = result.Count;
            return result;
        }

        #region 查询-单表单个实体
        /// 
        /// 查询-单表单个实体
        /// 
        private void GetModel()
        {
            Expression> predicate = s => s.UserId == 60159;
            var model = _testContext.User.FirstOrDefault();
            model = _testContext.User.Where(predicate).FirstOrDefault();
        }
        #endregion

        #region 查询-单表列表
        /// 
        /// 查询-单表列表
        /// 
        private void GetModelList()
        {
            var model = _testContext.User.ToList();
        }
        #endregion

        #region 查询-单表分页
        /// 
        /// 查询-单表分页
        /// 当前页码
        /// 每页显示记录数
        /// 
        private void GetModelPage(int page, int pageSize)
        {
            int skipCount = 0;
            if (page > 1)
            {
                skipCount = (page - 1) * pageSize;
            }
            var sw = new Stopwatch();
            sw.Start();

            List users = _testContext.User.Skip(skipCount).Take(pageSize).ToList();
            sw.Stop();
            ViewBag.spanTime = sw.Elapsed.TotalSeconds;
            ViewBag.dataCount = users.Count;
        }
        #endregion

        #region 查询-多表左右连接
        /// 
        /// 查询-多表左右连接
        /// 
        private object GetModelJoinList()
        {
            var sw = new Stopwatch();
            sw.Start();
            //Join
            //var result = (from user in _testContext.User
            //               join myUsergroup in _testContext.Usergroup on user.UserGroup equals myUsergroup.GroupId 
            //              //条件查询
            //             // where user.UserId>60150 && user.UserId<
            //              select new
            //              {
            //                  user.UserId,
            //                  user.CreateTime,
            //                  user.UserGroup,
            //                  user.UserNo,
            //                  user.UserName,
            //                  myname = myUsergroup.GroupName
            //              }).ToList();
            //return result;

            //left Join+分页
            //var result = (from user in _testContext.User
            //              join myUsergroup in _testContext.Usergroup on user.UserGroup equals myUsergroup.GroupId into ud
            //              from a in ud.DefaultIfEmpty()
            //              orderby user.UserId 
            //              where (user.UserId>60150 && user.UserId<70150)                                                       
            //              select new
            //              {
            //                  user.UserId,
            //                  user.CreateTime,
            //                  user.UserGroup,
            //                  user.UserNo,
            //                  user.UserName,
            //                  a.GroupName
            //              }).Skip(1000).Take(10).ToList();
            //sw.Stop();
            //ViewBag.spanTime = sw.Elapsed.TotalSeconds;
            //ViewBag.dataCount = result.Count;
            //return result;

            //group by
            var result = (from user in _testContext.User
                          group user by user.UserGroup
                into g
                          select new
                          {
                              g.Key,
                              total = g.Count()
                          }).ToList();
            sw.Stop();
            ViewBag.spanTime = sw.Elapsed.TotalSeconds;
            ViewBag.dataCount = result.Count;
            return result;
        }
        #endregion

你可能感兴趣的:(EF,Core)