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.
 
 
 

52 lines
2.0 KiB

  1. using System;
  2. using System.Data.SqlClient;
  3. namespace DotNetCore.CAP.EntityFrameworkCore.Test
  4. {
  5. public static class ConnectionUtil
  6. {
  7. private const string DatabaseVariable = "Cap_SqlServer_DatabaseName";
  8. private const string ConnectionStringTemplateVariable = "Cap_SqlServer_ConnectionStringTemplate";
  9. private const string MasterDatabaseName = "master";
  10. private const string DefaultDatabaseName = @"DotNetCore.CAP.EntityFrameworkCore.Test";
  11. //private const string DefaultConnectionStringTemplate = @"Server=.\sqlexpress;Database={0};Trusted_Connection=True;";
  12. private const string DefaultConnectionStringTemplate = @"Server=192.168.2.206;Initial Catalog={0};User Id=sa;Password=123123;MultipleActiveResultSets=True";
  13. public static string GetDatabaseName()
  14. {
  15. return Environment.GetEnvironmentVariable(DatabaseVariable) ?? DefaultDatabaseName;
  16. }
  17. public static string GetMasterConnectionString()
  18. {
  19. return string.Format(GetConnectionStringTemplate(), MasterDatabaseName);
  20. }
  21. public static string GetConnectionString()
  22. {
  23. //if (Environment.GetEnvironmentVariable("ASPNETCore_Environment") == "Development")
  24. //{
  25. // return "Server=192.168.2.206;Initial Catalog=Test2;User Id=cmswuliu;Password=h7xY81agBn*Veiu3;MultipleActiveResultSets=True";
  26. //}
  27. return string.Format(GetConnectionStringTemplate(), GetDatabaseName());
  28. }
  29. private static string GetConnectionStringTemplate()
  30. {
  31. return
  32. Environment.GetEnvironmentVariable(ConnectionStringTemplateVariable) ??
  33. DefaultConnectionStringTemplate;
  34. }
  35. public static SqlConnection CreateConnection(string connectionString = null)
  36. {
  37. connectionString = connectionString ?? GetConnectionString();
  38. var connection = new SqlConnection(connectionString);
  39. connection.Open();
  40. return connection;
  41. }
  42. }
  43. }