static void Main(string[] args) { //创建修改的对象 Users change = new Users() { UNum = 10000, UName = "admin", UPass = "******" }; using (EFDemoEntities db = new EFDemoEntities()) { //将对象加入EF容器 DbEntityEntry entity = db.Entry <Users>(change); //设置对象状态 entity.State = System.Data.EntityState.Unchanged; //Modified状态 设置被修改的列 entity.Property("UNum").IsModified = false; entity.Property("UName").IsModified = true; entity.Property("UPass").IsModified = true; //保存修改 db.SaveChanges(); Console.WriteLine("数据修改成功!"); } }
/// <summary> /// 返回根据Lambda表达式排序后的用户表 /// </summary> /// <typeparam name="TKey">排序字段类型</typeparam> /// <param name="where">数据查询条件</param> /// <param name="lambda">数据排序条件</param> /// <returns></returns> private static List <Users> GetListByOrder <TKey>(Expression <Func <Users, bool> > where, Expression <Func <Users, TKey> > lambda) { using (EFDemoEntities db = new EFDemoEntities()) { return(db.Users.Where(where).OrderBy(lambda).ToList()); } }
/// <summary> /// 分页查询 /// </summary> /// <typeparam name="Tkey">排序列的数据类型</typeparam> /// <param name="pageIndex">当前页索引</param> /// <param name="pageSize">每页显示的数量</param> /// <param name="where">查询范围表达式</param> /// <param name="order">排序表达式</param> /// <returns></returns> private static List <Users> GetPage <Tkey>(int pageIndex, int pageSize, Expression <Func <Users, bool> > where, Expression <Func <Users, Tkey> > order) { using (EFDemoEntities db = new EFDemoEntities()) { return(db.Users.Where(where).OrderBy(order).Skip(pageIndex * pageSize).Take(pageSize).ToList()); } }
static void Main(string[] args) { using (EFDemoEntities db = new EFDemoEntities()) { DbQuery <Users> query = db.Users.Where(u => u.UName == "admin") as DbQuery <Users>; Users admin = query.FirstOrDefault(); Console.WriteLine("\t 编号 \t 账户 \t 密码"); Console.WriteLine("\t {0} \t {1} \t {2}", admin.UNum, admin.UName, admin.UPass); } }
static void Main(string[] args) { using (EFDemoEntities db = new EFDemoEntities()) { //创建需要删除的对象 Users del = new Users() { UNum = 10001 }; //附加到EF中 db.Users.Attach(del); //标记为删除 db.Users.Remove(del); //提交修改 db.SaveChanges(); Console.WriteLine("数据删除成功!"); } }
static void Main(string[] args) { using (EFDemoEntities db = new EFDemoEntities()) { //循环添加50个账户 for (int i = 0; i < 50; i++) { Users u = new Users() { UName = "Test" + i, UPass = "******" + i, }; db.Users.Add(u); } //保存更改 //批处理 多次添加 一次实现 db.SaveChanges(); Console.WriteLine("数据添加成功!"); } }