Saturday, 25 December 2021

Access Connection String In DbContext File From appsettings.json C# In Asp.Net Core 6

12/25/2021 - By Pranav Singh 0

 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.

Access Connection String In DbContext File From appsettings.json C# In Asp.Net Core 6

About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

0 comments:

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top