In this article I will show you how you can access connection string in your DBContext file from appsettings.json c# in you asp.net core 6. So for this we will create a new asp.net core application and we will add a connection string in your appsetting.json file.
"ConnectionStrings": {
"connection": "Server=\\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;” } |
Now here is
the code which we will user to access the connection string placed in your appsettings.json
file in .net core application. Now in your context file add the below code to access
the connection string. This will help you to make your connection string configurable.
var builder = new
ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json",
optional: false); IConfiguration config = builder.Build(); string mysqlconection =
config.GetValue<string>("ConnectionStrings:sqlconnection");
optionsBuilder.UseSqlServer(mysqlconection); |
Now for
this you need to add the below mention name space.
using
System.IO; using
Microsoft.Extensions.Configuration; |
Now we have done. Just run the application and check t output.
0 comments:
Please let me know your view