In this article let us look at how to Provide Database Connection String in Entity Framework(EF) Core Applications. The DBContext connects to the database using the Database Providers. These Providers requires a connection string to connect to the database.
The way the connection string is specified has changed from the previous version of the entity framework. You can read it Database connection string in Entity Framework
There are several ways by which you can provide
Table of Contents
Where to Store the connection strings
The connection strings were stored in web.config file in older version of ASP.NET Applications.
The newer ASP.NET Core applications can read the configurations from the various sources like appsettings.json, user secrets, environment variables, command line arguments etc. You can store connection string anywhere you wish to. For this example, we will use the appsettings.json
Connection string in appsettngs.json
The appsettings.json can be created for each environment separately
The appsetting.json holds the settings that are common to all the environments like development, production & testing environment
The appsettings<environmentName>.json file holds the settings that are used in the environment specified by the ASPNETCORE_ENVIRONMENT variable. For example, appsettings.production.json holds the settings for the production environment and appsettings.development.json holds the settings for the development environment
The configuration is stored in name-value pairs. These name-value pairs into a structured hierarchy of sections. Hence each connection string is stored as a separate node under the section ConnectionStrings as shown below
1 2 3 4 5 6 7 8 9 | { "ConnectionStrings" : { "MySQLConnection": "server=localhost;uid=root;pwd=12345;database=EFCore", "SQLConnection": ""Server=(localdb)\\MSSQLLocalDB;Database=EFCore;Trusted_Connection=True;MultipleActiveResultSets=true" } } |
There is no requirement to name the section as “ConnectionStrings”. You can name whatever you want it to be. But naming it ConnectionStrings allows us to make use of the getConnectionString method of the IConfiguration object
Passing Connection String to DBContext
You can create DBContext and configure it by passing the connection string in several ways depending on the type of application (like ASP.NET Core MVC Apps or Console Apps) and whether you want to make use of Dependency Injection or not.
ASP.NET Core MVC Application
In MVC Application, the DBContext is injected using the Dependency Injection. To do that we need to register the DBContext in the ConfigureServices method of the startup class. Hence we also need to read the Connection String in startup class.
Reading the Connection string in the startup class
To Read the from the configuration, we need an instance of IConfiguration object. The IConfiguration is available to be injected via Dependency injection.
Hence, we can inject it into the startup class using the constructor as shown below
1 2 3 4 5 6 7 8 9 | public static IConfiguration Configuration { get; set; } public Startup(IConfiguration config) { Configuration = config; } |
You can read it as shown below
1 2 3 4 | Configuration.GetSection("ConnectionStrings:MySQLConnection") Configuration.GetSection("ConnectionStrings:SQLConnection") |
Or by using the GetConnectionString method as shown below. (Provided
1 2 3 | var connectionString = Configuration.GetConnectionString("SQLConnection"); |
Passing the Connection string to DBContext
We create our own Context class by inheriting from the DBContext
1 2 3 4 5 6 7 8 9 10 | public class EFContext : DbContext { public EFContext(DbContextOptions options) : base(options) { } public DbSet<Product> Products { get; set; } } |
Note that EFContext constructor requires the instance of the DbContextOptions. The DbContextOptions contains the configuration information such as type of database to use, connection string etc.
Next, we need to register the EFContext for Dependency injection. This done in the ConfigureServices method of the startup class.
1 2 3 4 5 6 7 8 9 10 11 12 | public void ConfigureServices(IServiceCollection services) { services.AddMvc(); var connectionString = Configuration.GetConnectionString("SQLConnection"); services.AddDbContext<EFContext>( options => options.UseSqlServer(connectionString) ); |
The AddDBContext extension method provided by entity framework core is used to register our Context class. The first argument is of Actiion<T>, where you get the reference to the DbContextOptionsBuilder. The DbContextOptionsBuilder is used to configure the DbContextOptions. Here we use UseSqlServer method to register the SQL Server as the database provider, passing the connection string along with it.
Finally, you can use the DBContext by injecting it in the constructor of the Controller or services etc as shown below.
1 2 3 4 5 6 7 8 9 | private EFContext db; public HomeController(EFContext EFContext) { db = EFContext; } |
.NET Core Console Application
The ASP.NET Core MVC Template configures the Dependency Injection automatically for us. But in
Appsettings.json in .NET Core Console applications
The appsettings.json file is not created in the console applications. Hence you need to create it first.
The appsettings.json file is not copied to the output directory when you run the Console application in Visual Studio. To do that select the appsettings.json and right-click to select the properties. Select the property “Copy to output directory” and change the value “copy always” or “Copy if newer”
Reading the Connection String in the .NET Core application
To Read the connection string, we need to initialize and build the instance of the IConfiguration. To do that first we need to install the following packages
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.FileExtensions
- Microsoft.Extensions.Configuration.Json
Then, you can use the following code to read the connection string, wherever you need them
1 2 3 4 5 6 7 8 | var builder = new ConfigurationBuilder(); builder.AddJsonFile("appsettings.json", optional: false); var configuration = builder.Build(); connectionString = configuration.GetConnectionString("SQLConnection"); |
First, we create the instance of ConfigurationBuilder
1 2 3 | var builder = new ConfigurationBuilder(); |
Next, we add the various configuration sources to the ConfigurationBuilder. The following code adds the appsettings.json file.
1 2 3 | builder.AddJsonFile("appsettings.json", optional: false); |
Finally, call the build method, which returns the configuration object, which is an instance of the IConfiguration
1 2 3 | var configuration = builder.Build(); |
Finally, you can read the connection string from the configuration object
1 2 3 | connectionString = configuration.GetConnectionString("SQLConnection"); |
Passing the connection string to DBContext
Create the Context class as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class EFContext : DbContext { private string connectionString ; public EFContext() : base() { var builder = new ConfigurationBuilder(); builder.AddJsonFile("appsettings.json", optional: false); var configuration = builder.Build(); connectionString = configuration.GetConnectionString("SQLConnection").ToString(); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(connectionString); } public DbSet<Product> Products { get; set; } } |
Summary
We looked at how to provide the connection string to our context class in both ASP.NET Core web application and also in .NET Core console application. In the next article, we will explore the DBContext in more detail.
thanks i love u