SQL Connection

We need to link our Visual Studio project with the SQL database.  This is achieved by ascertaining a 'Connection String' from the SQL database and then entering this into appsettings.json and making a couple of other configuration changes.

SQL Connection String

  • Open Visual Studio and open the BlazorCountries project (if not already open).
  • Select View > SQL Server Object Explorer
  • Click the 'Add SQL Server' button
  • Select the appropriate SQL Server
  • Optionally, select the default Database Name (doesn't seem to matter) and click 'Connect'
  • In the SQL Server Object Explorer, expand the tree, highlight CountriesDb and right-click and select 'Properties'.
  • From the Properties pane copy the whole of the 'Connection String'
  • Close the SQL Server Object Explorer.

appsettings.json

Using Solution Explorer, open 'appsettings.json' and add the following section, substituting the string just copied from the SQL Server Object Explorer for 'Your connection string here'

"ConnectionStrings":{
     "SqlDBcontext" : "Your connection string here"
}

Note that the name of the connection string we have just defined in appsettings.json is 'SqlDBcontext'.  This is required in the next section.

SqlConnectionConfiguration.cs

In the Data folder add a new class called 'SqlConnectionConfiguration.cs' and paste in the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlazorCountries.Data
{
    public class SqlConnectionConfiguration
    {
        public SqlConnectionConfiguration(string value) => Value = value;
        public string Value { get; }
    }
}

Startup.cs

In 'Startup.cs', below 'services.AddSingleton<WeatherForecastService();', add the following code.  The 'WeatherForecast' line can be deleted as isn't needed.

var sqlConnectionConfiguration = new SqlConnectionConfiguration(Configuration.GetConnectionString("SqlDBContext"));
services.AddSingleton(sqlConnectionConfiguration);