Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

EntityFramework Configuration Provider for .NET Framework & .NET Core

5.00/5 (4 votes)
25 Oct 2016CPOL4 min read 22.5K  
Configuration.EntityFramework is a custom configuration provider for the .NET Core Configuration system built on EntityFrameworkCore.

Configuration.EntityFrameworkonfiguration.EntityFramework

Introduction

.NET Core supports a variety of different configuration options. Application configuration data can come from files using built-in support for JSON, XML, and INI formats, as well as from environment variables, command line arguments or even an in-memory collection. So why is there no support for EntityFramework? Well, now there is!

Configuration.EntityFramework is a custom configuration provider for the .NET Core Configuration system. It's built on EntityFrameworkCore allowing configuration settings to be stored in a wide variety of repositories.

Some settings, such as a connection string or those required during the initialization of an application may be better located in a local file rather than a repository. However, in many cases, Configuration.EntityFramework can present some distinct advantages, including:

  1. Makes use of the .NET Core configuration provider model,
  2. Support for complex types,
  3. Access settings in a strongly typed fashion using the Options pattern,
  4. Enhanced Configuration Management and Change Control. This is particularly relevant to a distributed environment,
  5. Transactional update of settings for whole of environment,
  6. Common settings can be shared among many applications. Support for single point of change,
  7. In a complex system with many related applications or services, it's not uncommon to have many configuration files. By persisting settings to a database, the dependency on these configuration files can be reduced,
  8. All settings for a select criteria, such as environment, application or section can be retrieved with a single query,
  9. Allow end users to update settings via the EntityFramework Context.

Background

Some Use Cases for adopting Configuration.EntityFramework

There are many compelling use cases for using Configuration.EntityFramework and persisting your settings to a database. However, we'll cover just a few here.

Deep Software Stack

In many cases, particularly enterprise systems, the software stack may be comprised of many parts, for example a Windows Service, Web Application, Web API and Desktop Application. Each of these parts will most likely have its own configuration file which must be deployed and maintained. With Configuration.EntityFramework, the settings related to these parts can be centrally stored and maintained, reducing the effort and risk associated with software deployment, upgrades and frequent or occasional configuration changes.

Distributed Solution

In a distributed solution, configuration files will exist on more than one server. In the case of a clustered environment, the same configuration files may be duplicated across many servers, all of which could be identical. With Configuration.EntityFramework, settings can be managed from a single source of truth but utilized by any resource.

Release Management

Configuration Files can add additional complexity to the Release Management process. When adding, removing or modifying settings, there are many variables to consider, including;

  • Versioning
  • Has a setting been modified by the client since last deployed
  • Is a conditional merge required

As Configuration.EntityFramework leverages EntityFrameworkCore for the persistence of Configuration Settings to a relational database, configuration data can be managed in many ways, including scripting or via the EF ConfigurationContext.

Atomic Update

Where there are many configuration files, potentially located on many servers, maintaining the integrity of these files is essential. To make a change to just one setting, a well considered backup and restore strategy (recovery plan) is a must. However, by persisting these settings to a database, the logistics involved and the system outage necessary to make the change is greatly reduced.

Using the Code

Getting started couldn't be more easy.

Step 1

Install the latest Nuget Package.

Step 2

Create a Repository compatible with EntityFrameworkCore and the ConfigurationContext.

Step 3

Add your settings to the repository.

Step 4

Register and initialize the Configuration.EntityFramework provider with the IConfiguration instance. This is done by calling the AddEntityFrameworkConfig extension method on the ConfigurationBuilder.

C#
var config = new ConfigurationBuilder()
   .SetBasePath(Environment.CurrentDirectory)
   .AddJsonFile("appsettings.json", true, true)
   .AddEntityFrameworkConfig(builder => builder.UseSqlServer
   (@"Data Source=.;Initial Catalog=Configuration;Integrated Security=True"))
   .Build();

Quick Start

Having completed steps 1 - 4, you are now ready to start accessing your settings.

The following snippets provide sample code for retrieving your settings via the IConfiguration instance which is returned by the ConfigurationBuilder.Build() method.

Check Configuration Section Exists.

C#
var exists = config.SectionExists("SampleSection");

Get Configuration Section for complex type. Return null if section does not exist.

C#
var section = config.TryGetSection<ComplexType>("SampleSection");

Get Configuration Section for complex type. Return default value if section does not exist.

C#
var section = config.GetSection<ComplexType>("SampleSection");

Get Configuration Value for Key.

C#
var setting = config.GetValue<string>("TestSetting");

Configuring the ConnectionString

As the Configuration.EntityFramework provider is retrieving settings persisted to a database, a ConnectionString is required. This ConnectionString can be configured via the DbContextOptionBuilder as in the following sample.

C#
var config = new ConfigurationBuilder()
   .AddEntityFrameworkConfig(builder => 
    builder.UseSqlServer(@"Data Source=.;Initial Catalog=Configuration;Integrated Security=True"))
   .Build();

Alternatively, a ConnectionString can be added to the local config settings. In the case of an .xproj project, this would mean the appsettings.json file.

C#
{
  "ConnectionStrings": {
    "ConfigurationContext": "Data Source=.;Initial Catalog=Configuration.Samples;
     Integrated Security=True"
  }
}

Points of Interest

Visit our wiki for more information, including:

  1. The database schema
  2. The domain model
  3. How-to create the repository
  4. How-to add settings to the repository
  5. How-to get settings for an application
  6. How-to get started
  7. Common use cases

Download the latest sample code from GitHub.

History

  • 21st October, 2016: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)