EF基本操作增、删、查、改、分页,join……等

一、批量添加数据

  1         static void Main(string[] args)
  2         {
  3             add();
  4             add2();
  5             Console.ReadKey();
  6         }
  7 
  8         static void add()
  9         {
 10             DemoDbEntities db = new DemoDbEntities();
 11             Stopwatch st = new Stopwatch();
 12             st.Start();
 13             for (int i = 0; i < 1000; i++)
 14             {
 15                 db.User.Add(new User { NAME = "张三" +i, AGE = i });
 16                 db.SaveChanges();
 17             }
 18             st.Stop();
 19             Console.WriteLine("用时:{0}毫秒", st.ElapsedMilliseconds);
 20 
 21 
 22         }
 23 
 24         static void add2()
 25         {
 26             DemoDbEntities db = new DemoDbEntities();
 27             Stopwatch st = new Stopwatch();
 28             st.Start();
 29             for (int i = 0; i < 1000; i++)
 30             {
 31                 db.User.Add(new User { NAME = "张三" + i,AGE=i });
 32 
 33             }
 34             db.SaveChanges();
 35             st.Stop();
 36             Console.WriteLine("用时:{0}毫秒", st.ElapsedMilliseconds);
 37 
 38         }
View Code

image

通过以上的对比发现,如果每次新增加一个条数据,就用EF SaveChanges 一次,这样会很消耗性能,可以全部标记完了之后,再去调用SaveChanges方法保存数据,这样性能会有所提高。

二、批量删除

  1  static void Main(string[] args)
  2         {
  3             del();
  4             Console.ReadKey();
  5         }
  6 
  7         #region EF批量删除
  8         static void del()
  9         {
 10             DemoDbEntities db = new DemoDbEntities();
 11 
 12             List<User> list = db.User.Where(u => u.NAME == "张三1").ToList();
 13             //Any表示只要集合中有值就返回true 否者返回float
 14             if (list != null && list.Any())
 15             {
 16                 foreach (User item in list)
 17                 {
 18                     db.User.Remove(item);
 19                 }
 20                 db.SaveChanges();
 21             }
 22             Console.WriteLine("删除成功");
 23         }
 24         #endregion
View Code

先查询出结果,保证数据库中有值,再删除。

三、EF编辑数据

第一种方式是查询之后在编辑;

第二种方式直接传入一个需要修改的model实体,可以是部分字段

  1 static void Main(string[] args)
  2         {
  3             edit2();
  4             Console.ReadKey();
  5         }
  6         #region EF编辑数据
  7         static void edit()
  8         {
  9             DemoDbEntities db = new DemoDbEntities();
 10 
 11             var model = db.User.FirstOrDefault(u => u.NAME == "张三3");
 12             model.NAME = "李四";
 13             db.SaveChanges();
 14             Console.WriteLine("编辑成功");
 15         }
 16         static void edit2()
 17         {
 18             DemoDbEntities db = new DemoDbEntities();
 19 
 20             User model = new User() {
 21                 ID=4,
 22                 NAME="王五"
 23             };
 24             //获取代理对象类的状态为Detaceh
 25             System.Data.Entity.Infrastructure.DbEntityEntry entry = db.Entry(model);
 26             //1、将代理类的状态修改成 Unchanged 2、将代理类中的需要更新的字段的IsModified修改成true
 27             entry.State = System.Data.Entity.EntityState.Unchanged;
 28             entry.Property("NAME").IsModified = true;
 29             //解决对一个或多个实体验证失败 的方法:关闭EF的实体合法性检查
 30             db.Configuration.ValidateOnSaveEnabled = false;
 31             db.SaveChanges();
 32             Console.WriteLine("编辑成功");
 33         }
 34         #endregion
View Code

四、EF中join的使用方法

  1   static void Main(string[] args)
  2         {
  3             efjoin2();
  4             Console.ReadKey();
  5         }
  6 
  7         #region  EF连表查询的2种方式
  8         static void efjoin()
  9         {
 10             DemoDbEntities db = new DemoDbEntities();
 11 
 12             var sql = db.User.Join(db.GroupInfo, u => u.GroupinfoID, g => g.ID, (c, g) => new {uername=c.NAME,g.NAME });
 13 
 14             var list = sql.ToList();
 15 
 16             list.ForEach(c => Console.WriteLine(c.uername+""+c.NAME));
 17         }
 18         static void efjoin2()
 19         {
 20             DemoDbEntities db = new DemoDbEntities();
 21 
 22             db.User.Include("GroupInfo").Where(c => true).ToList().ForEach(c => Console.WriteLine(c.NAME + "" + c.GroupInfo.NAME));
 23 
 24         }
 25         #endregion
View Code

五、 EF分页查询

  1        static void Main(string[] args)
  2         {
  3             fenye();
  4             Console.ReadKey();
  5         }
  6 
  7         #region EF分页
  8         static void fenye()
  9         {
 10             DemoDbEntities db = new DemoDbEntities();
 11             //在分页前先要是用OrderBy或者OrderByDescending对数据进行正序或者倒序然后在skip()跳过多少条,take()查询多少条。
 12             db.User.OrderBy(u => u.ID).Skip(0).Take(5).ToList().ForEach(c=>Console.WriteLine(c.ID));
 13         }
 14         #endregion
View Code

六、EF存储过程的调用

  1         static void Main(string[] args)
  2         {
  3             cunchu();
  4             Console.ReadKey();
  5         }
  6 
  7         #region EF存储过程的使用
  8         static void cunchu()
  9         {
 10             DemoDbEntities db = new DemoDbEntities();
 11             //调用存储过程USP_GetPagedArticleList
 12             int count = 0;
 13             //由于totalItems是一个输出参数,所以由程序员自己定义
 14             ObjectParameter ps = new ObjectParameter("totalItems", count);
 15 
 16             db.USP_GetPagedArticleList(1, 2, ps).ToList().ForEach(u=>Console.WriteLine(u.ID));
 17 
 18             Console.WriteLine("总行数=" + ps.Value);
 19         }
 20         #endregion
View Code

七、EF中执行SQL

  1        static void Main(string[] args)
  2         {
  3             EFtoSql();
  4             Console.ReadKey();
  5         }
  6 
  7         #region EF中执行SQL语句
  8         static void EFtoSql()
  9         {
 10             DemoDbEntities db = new DemoDbEntities();
 11             string sql = "update [DemoDb].[dbo].[User] set NAME=@name where ID>@id";
 12 
 13             SqlParameter[] p = new SqlParameter[] {
 14                 new SqlParameter("@id",5),
 15                  new SqlParameter("@name","王五")
 16             };
 17             db.Database.ExecuteSqlCommand(sql,p);
 18             Console.WriteLine("修改成功");
 19         }
 20 
 21         #endregion
View Code

八 EF提高查询的方法AsNoTracking

  1         static void Main(string[] args)
  2         {
  3             EFAsNoTracking();
  4             Console.ReadKey();
  5         }
  6         #region EF不跟踪查询AsNoTracking()
  7         static void EFAsNoTracking()
  8         {
  9             DemoDbEntities db = new DemoDbEntities();
 10             //使用AsNoTracking()可以提高查询效率,不用在DbContext中进行缓存
 11             db.User.AsNoTracking().Where(u => u.ID > 5).ToList().ForEach(c => Console.WriteLine(c.ID));
 12         }
 13         #endregion
View Code

九、EF上下文容器中Set<T>泛型方法的使用

  1         static void Main(string[] args)
  2         {
  3             EFSet();
  4             Console.ReadKey();
  5         }
  6 
  7         #region EF上下文容器中的Set<T>泛型方法的作用
  8         static void EFSet()
  9         {
 10             DemoDbEntities db = new DemoDbEntities();
 11             //db.Set<User> 相当于db.User
 12             db.Set<User>().Where(u => u.ID > 5).ToList().ForEach(c => Console.WriteLine(c.ID));
 13         }
 14         #endregion
View Code

转载于:https://www.cnblogs.com/M-LittleBird/p/5852395.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
EF(Entity Framework)是.NET Framework中的一种ORM(Object Relational Mapping)框架,可以用来简化数据库操作。下面是使用EF Web API进行的示例代码: 1. 加数据: ```csharp [HttpPost] public async Task<IActionResult> AddData([FromBody] Data data) { if (!ModelState.IsValid) { return BadRequest(ModelState); } _context.Data.Add(data); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(GetData), new { id = data.Id }, data); } ``` 2. 除数据: ```csharp [HttpDelete("{id}")] public async Task<IActionResult> DeleteData(int id) { var data = await _context.Data.FindAsync(id); if (data == null) { return NotFound(); } _context.Data.Remove(data); await _context.SaveChangesAsync(); return NoContent(); } ``` 3. 修数据: ```csharp [HttpPut("{id}")] public async Task<IActionResult> UpdateData(int id, [FromBody] Data data) { if (id != data.Id) { return BadRequest(); } _context.Entry(data).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!_context.Data.Any(e => e.Id == id)) { return NotFound(); } else { throw; } } return NoContent(); } ``` 4. 询数据: ```csharp [HttpGet("{id}")] public async Task<ActionResult<Data>> GetData(int id) { var data = await _context.Data.FindAsync(id); if (data == null) { return NotFound(); } return data; } ``` 以上是EF Web API进行的示例代码,需要注意的是,这只是示例代码,具体实现还需要根据具体的业务逻辑进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值