SqlQueryExtension.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Common;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Microsoft.EntityFrameworkCore;
  8. using YiSha.Util;
  9. namespace YiSha.Data.EF
  10. {
  11. public static class SqlQueryExtension
  12. {
  13. public static async Task<IList<T>> SqlQuery<T>(this DbContext db, string sql, params object[] parameters) where T : class
  14. {
  15. using (var db2 = new ContextForQueryType<T>(db.Database.GetDbConnection()))
  16. {
  17. return await db2.Set<T>().FromSqlRaw(sql, parameters).ToListAsync();
  18. }
  19. }
  20. private class ContextForQueryType<T> : DbContext where T : class
  21. {
  22. private readonly DbConnection connection;
  23. public ContextForQueryType(DbConnection connection)
  24. {
  25. this.connection = connection;
  26. }
  27. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  28. {
  29. // switch on the connection type name to enable support multiple providers
  30. string dbType = GlobalContext.SystemConfig.SystemDBProvider;
  31. switch (dbType)
  32. {
  33. case "SqlServer":
  34. optionsBuilder.UseSqlServer(connection, options => options.EnableRetryOnFailure()) ;
  35. break;
  36. case "MySql":
  37. optionsBuilder.UseMySql(connection, options => options.EnableRetryOnFailure());
  38. break;
  39. case "Oracle":
  40. break;
  41. default:
  42. throw new Exception("未找到数据库配置");
  43. }
  44. base.OnConfiguring(optionsBuilder);
  45. }
  46. protected override void OnModelCreating(ModelBuilder modelBuilder)
  47. {
  48. modelBuilder.Entity<T>(p =>
  49. {
  50. p.HasNoKey();
  51. });
  52. base.OnModelCreating(modelBuilder);
  53. }
  54. }
  55. }
  56. }