查询
cs
/// <summary>
/// 查询
/// </summary>
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<UserInfo> list = new List<UserInfo>();
foreach (var userInfo in UserInfoList)
{
list.Add(userInfo);
}
dgv.DataSource = list;
}
追加
cs
/// <summary>
/// 追加
/// </summary>
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>(userInfo).State = System.Data.Entity.EntityState.Added;
db.SaveChanges();
}
修改
cs
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>(userInfo).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
SQLLoad();
#endregion
}
删除
cs
/// <summary>
/// 删除
/// </summary>
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();
}
分页查询
cs
/// <summary>
/// 分页查询
/// </summary>
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 <= 0)
{
pageIndex = 1;
pageSize = 5;
txtIndex.Text = pageIndex.ToString();
txtSIze.Text = pageSize.ToString();
}
//分页查询一一定要排序
var userInfo = db.UserInfo.OrderBy(u => u.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
List<UserInfo> list = new List<UserInfo>();
foreach (var item in userInfo)
{
list.Add(item);
}
dgv.DataSource = list;
}