I am new to .NET Core, so forgive me if my question is so basic. I always use .NET Framework for my all project, but now I have to move to .NET Core 6. In .NET Framework, I set my connection string in Web.config like this:
<add key="ConnStr" value="Data Source=DESKTOP-854AIA7;Initial Catalog=TestOTA;User ID=sa;Password=1"/>
<add key="ConnStrReport" value="Data Source=192.168.5.226;Initial Catalog=cachrsp01;User ID=sa;Password=123@123"/>
<add key="ConnStrLog" value="Data Source=192.168.5.226;Initial Catalog=loghrsp01;User ID=sa;Password=123@123"/>
then I have a class to manage them like this :
public class AccessToDb{
public static string ConnectionString
{
get
{
string tmp = System.Configuration.ConfigurationManager.AppSettings["ConnStr"];
if (string.IsNullOrEmpty(tmp))
{
do something
}
return tmp;
}
}
public static string ConnectionStringLog
{
get
{
string tmp = System.Configuration.ConfigurationManager.AppSettings["ConnStrLog"];
if (string.IsNullOrEmpty(tmp))
{
do something
}
return tmp;
}
}
}
In other classes when I need to call them, depends on which one I need I call them like:
objSqlCommand.Connection = new SqlConnection(AccessToDb.ConnectionString);
or
objSqlCommand.Connection = new SqlConnection(AccessToDb.ConnectionStringLog);
But I don't know where to set my Connection string and where to call them and how to use it in my methods. I search but all results I found, used entity framework.
UPDATE
I checked and finally find a way around it. I add this in appsettings.json :
{
"ConnectionStrings": {
"mymainDB": "server=192.168.5.226;database=cachrsp01;user id=sa;password='123@123'",
"myLogDB": "server=192.168.5.226;database=loghrsp01;user id=sa;password='123@123'"
}
}
then I created Class AccessToDb like this:
public class AccessToDb
{
public static string ConnectionString { get; set; }
public static string ConnectionStringLog { get; set; }
}
Finally in Program.cs I configure them:
AccessToDb.ConnectionString = builder.Configuration.GetConnectionString("mymainDB");
AccessToDb.ConnectionStringLog = builder.Configuration.GetConnectionString("myLogDB");
everything now works fine for me.