鼎鼎知识库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

9、EF Core使用Sql语句提高查询效率.md 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 一种会报错的写法
  2. ```
  3. var macBreakerDatas = _breakerDataRepo.GetAll().Where(t => t.mac == mac.Mac);
  4. var removedBreakerDatas = macBreakerDatas.Where(t => (DateTime.Now - DateTime.Parse(t.CreateTime)).Minutes >= 65);
  5. _breakerDataRepo.RemoveRange(removedBreakerDatas);
  6. ```
  7. 不报错,但查询效率慢
  8. ```
  9. var macBreakerDatas = _breakerDataRepo.GetAll().Where(t => t.mac == mac.Mac);
  10. var removedBreakerDatas = macBreakerDatas.ToList().Where(t => (DateTime.Now - DateTime.Parse(t.CreateTime)).Minutes >= 65);
  11. _breakerDataRepo.RemoveRange(removedBreakerDatas);
  12. ```
  13. 修改基础设施层
  14. ```
  15. public interface IOpenBreakerDataRepository : IRepository<BreakerData, Guid>
  16. {
  17. IQueryable<BreakerData> GetAll();
  18. IQueryable<BreakerData> GetAllBySql(string sql);
  19. }
  20. public class OpenBreakerDataRepository : Repository<BreakerData, Guid, OpenAPIContext>, IOpenBreakerDataRepository
  21. {
  22. public OpenBreakerDataRepository(OpenAPIContext context) : base(context)
  23. {
  24. }
  25. public IQueryable<BreakerData> GetAll()
  26. {
  27. return DbContext.BreakerDatas.Where(t => true);
  28. }
  29. public IQueryable<BreakerData> GetAllBySql(string sql)
  30. {
  31. return DbContext.BreakerDatas.FromSqlRaw(sql);
  32. }
  33. }
  34. ```
  35. 最后改成
  36. ```
  37. string sixtyFiveAgoTimeStr = DateTime.Now.AddMinutes(-65).ToFullTimeStr();
  38. string rawSql = $"select * from breakerdatas where mac='{mac.Mac}' and str_to_date(CreateTime, '%Y-%m-%d %H:%i:%s') <= str_to_date('{sixtyFiveAgoTimeStr}', '%Y-%m-%d %H:%i:%s')";
  39. var removedBreakerDatas = _breakerDataRepo.GetAllBySql(rawSql);
  40. _breakerDataRepo.RemoveRange(removedBreakerDatas);
  41. ```