Database Connections In ASP.NET Core 2.0

Introduction

In this blog post, we will discuss three ways to define database connection string, get its values, and retrieve data in ASP.NET MVC core.

Details

We will just create a simple ASP.NET MVC Core web application.

For this, follow these steps in Visual Studio 2017.

  1. File > New > Project.
  2. Select ASP.NET Core Web Application.
  3. Set name and location
  4. In next screen, select Web Application (Model –>View –> Controller) Template, select "No Authentication", and click OK.

Now, add some necessary NuGet packages.

Tools - NuGet Package Manager - Package Manager Console
Run Install-Package Microsoft.EntityFrameworkCore.SqlServer

For Entity Framework Core Tools to create a database from your EF Core model:

Run Install-Package Microsoft.EntityFrameworkCore.Tools

And for ASP.NET Core Scaffolding tools to create Controllers and Views:

Run Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

If you are not already familiar with ASP.NET MVC Core web application development and have not developed even a single application, you should get a basic understanding of its development or read my blog by clicking here.

In previous versions of ASP.NET, we often used web.config for connection strings but in ASP.NET Core, we cannot use web.config for this purpose; rather, we can use other techniques or methods for it. Some of the simple methods are given below.

Method 1: Hard code connection string

The first and most basic method is to hard code the connection string into Startup.cs file as in the code below.

  1.  //Method 1 (Hard coded connection string)  
  2. var connection = @"Data Source=ATIQ;Initial Catalog=UserDB;Integrated Security=False;Persist Security Info=False;
  3. User ID=sa;Password=******";  
  4. services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connection));  
Method 2: Get connection string from appsettings.json
  1. //Method 2 (Get connection string from appsettings.json)  
  2. services.AddDbContext<MyDbContext>(options =>  
  3. options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  

where "DefaultConnection" is defined in appsetting.json at root directory of the application.

  1. {  
  2.   "Logging": {  
  3.     "IncludeScopes"false,  
  4.     "LogLevel": {  
  5.       "Default""Warning"  
  6.     }  
  7.   },  
  8.   "ConnectionStrings": {  
  9.     "DefaultConnection""Data Source=ATIQ;Initial Catalog=UserDB;Integrated Security=False;Persist Security Info=False;User ID=sa;Password=www@123"  
  10.   }  
  11. }  
Method 3: Get connection string from datasetting.json -- our custom JSON file

The third method is to get the string from custom JSON file and deserialize it for getting the values of connection string.

  1. //Method 3 (Get connection string from datasetting.json - our custom json file)  
  2.                        var settings = new DataSettingsManager().LoadSettings();  
  3.                        var connection = settings.DataConnectionString.ToString();  
  4.                        services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connection));  
Where "MyDbContext" is our data context class and "DataSettingsManager" is another class that saves serialized values of connection string in object "DataSettings." It looks like the following.
  1. public class MyDbContext : DbContext  
  2.     {  
  3.         public MyDbContext(DbContextOptions<MyDbContext> options)  
  4.             : base(options)  
  5.         { }  
  6.         public DbSet<MyUser> MyUser { get; set; }  
  7.     }  
  8.   
  9.     public class DataSettingsManager  
  10.     {  
  11.         private const string _dataSettingsFilePath = "App_Data/dataSettings.json";  
  12.         public virtual DataSettings LoadSettings()  
  13.         {  
  14.             var text = File.ReadAllText(_dataSettingsFilePath);  
  15.             if (string.IsNullOrEmpty(text))  
  16.                 return new DataSettings();  
  17.   
  18.             //get data settings from the JSON file  
  19.             DataSettings settings = JsonConvert.DeserializeObject<DataSettings>(text);  
  20.             return settings;  
  21.         }  
  22.   
  23.     }  
  24.   
  25.     public class DataSettings  
  26.     {  
  27.         public string DataConnectionString { get; set; }  
  28.     }  
You have to create a folder at the root directory named "App_Data" and create a JSON file named "datasettings.json" that has code like this:
  1. {  
  2.   "DataConnectionString""Data Source=ATIQ;Initial Catalog=UserDB;Integrated Security=False;
  3. Persist Security Info=False;User ID=sa;Password=******"  
  4. }  

Last Words

We can get any type of our custom settings or key values by using these methods in Asp.Net MVC Core.

All necessary code related files are attached to this blog post; just copy and paste into your project at the root. Please change connection string with your SQL Server in Startup.cs file. Also, modify the namespaces as your project name.