Configuring database connection and application configuration settings

To define connection strings, add the Application Configuration file known as appsettings.json and specify the SQL server connection string, as follows:

    { 
"ConnectionStrings": {
"DefaultConnection": "Data Source=.;
Initial Catalog=ERPDB; Integrated Security=True;"
}
}
Any database server's connection can be defined if it is supported by Entity Framework.

In the Startup class, we can now add this appsettings.json file to read all the key values defined and build a dictionary object that can be used to refer the connection string. Add the following code snippet in the Startup constructor:

    public Startup(IHostingEnvironment env) 
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json",
optional: true, reloadOnChange: true);
}

To resolve the SetBasePath and AddJsonFile methods, you have to add NuGet packages such as Microsoft.Extensions.Configuration.FileExtensions and Microsoft.Extensions.Configuration.Json.

The preceding code will only initialize and set the builder object to load the appsettings.json file. In order to access the keys, we have to call the builder.build method that returns IConfigurationRoot, which is a unified dictionary object and it can be used throughout the application to read configuration values. If multiple sources are specified in the ConfigurationBuilder object, all those sources, keys, and values will be combined into one dictionary object, known as IConfigurationRoot.

So, add this entry in the Startup constructor, as follows:

    Configuration = builder.Build();

And add the property in the Startup.cs, as follows:

    public IConfigurationRoot Configuration { get; }

IHostingEnvironment will be a dependency injected in the Startup constructor by the ASP.NET Core framework and it can also be used in scenarios such as if you have separate connection strings for development, staging, and production environments and you want to use the specific connection string based on the environment that your application is running on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.31.22