EF增删改查基础
#region 1.0 新增 -void Add() /// <summary> /// 1.0 新增 /// </summary> static void Add() { //1.1创建实体对象 User uObj = new User() { uName = "刘德华", uLoginName = "aaa", uPwd = "asdfasdfasdfsadf", uIsDel = false, uAddtime = DateTime.Now }; //1.2通过EF新增到数据库 //1.2.1将对象 加入到 数据上下文 的 User集合中 db.Users.Add(uObj); //1.2.2调用数据上下文 的 保存方法,将 对象 存数数据库 db.SaveChanges(); Console.WriteLine("保存成功~~!"); } #endregion #region 2.0 简单查询 -void Query() /// <summary> /// 2.0 简单查询 /// </summary> static void Query() { List<User> list = db.Users.Where(u => u.uName == "刘德华").ToList(); list.ForEach(u => Console.WriteLine(u.ToString())); } #endregion #region 3.0 官方推荐的 修改方式(先查询,再修改) /// <summary> /// 3.0 官方推荐的 修改方式(先查询,再修改) /// </summary> static void Edit() { //1.查询出一个 要修改的对象 User usr = db.Users.Where(u => u.uId == 1).FirstOrDefault(); Console.WriteLine("修改前:" + usr.ToString()); //2.修改内容 usr.uName = "刘德华"; usr.uLoginName = "liudehua"; //3.重新保存到数据库 db.SaveChanges(); Console.WriteLine("修改成功:"); Console.WriteLine(usr.ToString()); } #endregion #region 4.0 删除 -void Delete() /// <summary> /// 4.0 删除 /// </summary> static void Delete() { //4.1创建要删除的 对象 User u = new User() { uId = 6 }; //4.2附加到 EF中,Remove前必须Attach db.Users.Attach(u); //4.3标记为删除 db.Users.Remove(u); //4.4执行删除sql db.SaveChanges(); Console.WriteLine("删除成功~~~"); } #endregion
重写实体类ToString方法:
public partial class User { public override string ToString() { return this.uId + "," + this.uName + "," + this.uLoginName + "," + this.uPwd; } }
二、
//1.添加(增) EFDBEntities entity = new EFDBEntities(); Users users = new Users() { username = "aaa", password = "111" }; entity.Entry(users).State = EntityState.Added; entity.SaveChanges(); //2.删除(删) EFDBEntities entity = new EFDBEntities(); Users users = new Users() { id = 4 }; entity.Entry(users).State = EntityState.Deleted; entity.SaveChanges(); //3.修改(改) EFDBEntities entity = new EFDBEntities(); Users users = new Users() { id = 4, username = "rrr", password = "333" }; entity.Entry(users).State = EntityState.Modified; entity.SaveChanges(); //4.查询(查) //获取所有数据 var list = entity.Users; foreach (var item in list) { Console.WriteLine(item.id + "---" + item.username + "---" + item.password); } //第一种方法,查询id=1的数据 IQueryable<Users> list1 = from u in entity.Users where u.id == 1 select u; //第二种方法,查询id=1的数据 IQueryable<Users> list2 = entity.Users.Where(i => i.id == 3); //查询第一条数据 Users us = entity.Users.FirstOrDefault(); //遍历 foreach (var item in list1) { Console.WriteLine(item.id + "---" + item.username + "---" + item.password); }
总结:
static TextEntities db = new TextEntities();
1.添加:
Users user = new Users() { Id = 5, Name = "ppp", Pwd = "mmm", Gender = true, PowerId = 5 };
db.Users.Add(user); =======>这条语句等价于 db.Entry(user).State = EntityState.Added;
2.删除:
Users user = new Users() { Id = 5 };
db.Users.Attach(user);
db.Users.Remove(user);=======>这两条语句等价于 db.Entry(user).State = EntityState.Deleted;