查询
/// /// 查询/// private void SQLLoad(){//linq查询,方法一//var UserInfoList = from u in db.UserInfo//给个变量u,用来接收查询结果对象//select u;//查询结果对象 //db.UserInfo.Find(1);//依据主键查询,方法二//依据条件查询,如果数据返回类型是IQueryable说明是延迟查询,方法三//var UserInfoList = db.UserInfo.Where(u => u.ID > 0);//这里还没有开始查询//查询所有,方法四(不是延迟查询)var UserInfoList = db.UserInfo.ToList();List list = new List();foreach (var userInfo in UserInfoList){list.Add(userInfo);}dgv.DataSource = list;}
追加
/// /// 追加/// private void Add(){UserInfo userInfo = new UserInfo{UName = "heidashuai",UPwd = "123",SubTime = DateTime.Now,DelFlag = 0,ModifiedOn = DateTime.Now,Remark = "皮蛋",Sort = "21"};//db.UserInfo.Add(userInfo);db.Entry(userInfo).State = System.Data.Entity.EntityState.Added;db.SaveChanges();}
修改
private void AQLUpdate(){#region 官方推荐--修改已改变的//UserInfo userInfo = db.UserInfo.Where(u => u.ID == 1).FirstOrDefault();//返回的是UserInfo的代理类(包装类)//userInfo.UPwd = "8888";//到这一步时,包装类会给真实的类修改属性,并且会给他状态谁这位已修改状态//db.SaveChanges();查询//SQLLoad();#endregion#region 方式二--修改所有数据UserInfo userInfo = db.UserInfo.Where(u => u.ID == 1).FirstOrDefault();userInfo.Remark = "自律的人真帅!";db.Entry(userInfo).State = System.Data.Entity.EntityState.Modified;db.SaveChanges();SQLLoad();#endregion}
删除
/// /// 删除/// private void SQLDelete(){UserInfo userInfo = new UserInfo { ID = 21 };//也可以从数据库查询到//方式一//db.UserInfo.Attach(userInfo);//db.UserInfo.Remove(userInfo);//方式二//告诉上下文对此实体进行跟新操作db.Entry(userInfo).State = System.Data.Entity.EntityState.Deleted;//告诉上下文把实体的变化保存到数据库里面去db.SaveChanges();}
分页查询
/// /// 分页查询/// private void Paging(){int pageIndex = 0;int pageSize = 0;if (txtIndex.Text != "" && txtSIze.Text != ""){pageIndex = Convert.ToInt32(txtIndex.Text);pageSize = Convert.ToInt32(txtSIze.Text);}if (pageIndex <= 0 && pageSize u.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();List list = new List();foreach (var item in userInfo){list.Add(item);}dgv.DataSource = list;}