DbContext_Extensions_UseMySql.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System.Threading.Tasks;
  2. using Vitorm.MySql;
  3. using Vitorm.Sql;
  4. using Vitorm.Sql.SqlExecute;
  5. using Vitorm.Transaction;
  6. using DbConnection = MySqlConnector.MySqlConnection;
  7. namespace Vitorm
  8. {
  9. public static class DbContext_Extensions_UseMySql
  10. {
  11. public static SqlDbContext UseMySql(this SqlDbContext dbContext, string connectionString, int? commandTimeout = null)
  12. => UseMySql(dbContext, new DbConfig(connectionString: connectionString, commandTimeout: commandTimeout));
  13. public static SqlDbContext UseMySql(this SqlDbContext dbContext, DbConfig config)
  14. {
  15. dbContext.Init(
  16. sqlTranslateService: Vitorm.MySql.SqlTranslateService.Instance,
  17. dbConnectionProvider: config.ToDbConnectionProvider(),
  18. sqlExecutor: sqlExecutor
  19. );
  20. dbContext.createTransactionManager = createTransactionManager;
  21. if (config.commandTimeout.HasValue) dbContext.commandTimeout = config.commandTimeout.Value;
  22. return dbContext;
  23. }
  24. #region sqlExecutor
  25. static SqlExecutor sqlExecutor = new SqlExecutor() { CloseAsync = CloseAsync };
  26. static async Task CloseAsync(System.Data.Common.DbConnection conn)
  27. {
  28. if (conn is DbConnection mySqlConn)
  29. {
  30. await mySqlConn.CloseAsync();
  31. return;
  32. }
  33. conn.Close();
  34. }
  35. #endregion
  36. static ITransactionManager createTransactionManager(SqlDbContext dbContext) => new Vitorm.MySql.SqlTransactionManager(dbContext);
  37. static ITransactionManager createTransactionManager2(SqlDbContext dbContext) => new Vitorm.MySql.SqlTransactionManager_Command(dbContext);
  38. }
  39. }