This example demonstrates how to add an Entity Framework Core database context as a service using Dependency Injection (a form of Inversion of Control) in ASP.Net MVC Core 3.1. I’ve also include an example showing how to reference the database context from an MVC Controller. This example assumes you have already got at least one connection string called DefaultConnection in a configuration file (appsettings.json, appsettings.Development.json, etc.)

Some notes:

  • Microsoft recommends using the Repository pattern to further abstract the database access layer, in which case we would use the interface IProductsDb in the Dependency Injection instead of the concrete class ProductsDb. However, I’ve concluded after some research that the Repository Pattern is an unnecessary abstraction when using Entity Framework Core or even Entity Framework 6. Read more about that here.
  • The code below assumes you are using SQL Server and have the NutGet package Microsoft.EntityFrameworkCore.SqlServer installed in the project.

Create your model classes (here’s a simple example of one):

public class Widget {
    [Key]
    public int Id { get; set; }
    public String Name { get; set; }
}

Create the DBContext class:

public class ModelContext : DbContext {

    public ModelContext(DbContextOptions<ModelContext> options) : base(options) {
    }

    public DbSet<Widget> Widget { get; set; } // Singular is standard (not Widgets)
    public DbSet<Kitten> Kitten { get; set; }

}

Set up dependency injection by adding options.UseSqlServer() to ConfigureServices() in Startup.cs:

public void ConfigureServices(IServiceCollection services) {
  services.AddDbContext<ModelContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
  services.AddControllersWithViews();
}

Make DBContext accessible from within each controller by adding it to the controller class and setting it through the constructor:

private readonly ModelContext _context; // Add this line
public HomeController(ILogger<HomeController> logger, ModelContext context) { // Update this
  _logger = logger;
  _context = context; // Add this line
}
// Access _context in any method in this controller

Note: You can automatically generate most of the code required for a working controller by right-clicking the Controllers directory, clicking Add -> Controller, and selecting MVC Controller with views, using Entity Framework. The model injection shown above will automatically be included.

I’m personally not a fan of using the _ prefix for private fields, but that is the C# standard Microsoft is using in their templates for .Net Core 3, so I’m using it too.