Entity Framework Core logo

How to create a DbContext from just a connection string?

This post was most recently updated on April 13th, 2021.

3 min read.

When you’re in your .NET Core project, it’s always easy: you just register your DbContext in ConfigureServices, and then inject it into whichever Page, View or Controller you might need it in. However, when you have another project or solution you’re working on and you’d still like to use the same DbContext and your entity classes in it, you have to find another way to do it!

What should we do, then?

Description

Let’s first take a look at the use cases and tech stack. Or, alternatively, just jump straight to the Solution!

Why would you need your DbContext outside your original project?

There’s a lot of good reasons. While you could create a full data access layer and just reference it in your other projects, in a lot of cases it might make more sense to just reference your database context directly without actually building the services. You can’t do that with no dbcontext, however – you need to construct that in your referencing project.

How can we achieve this?

Instead of injecting the DbContext like in .NET Core web project, we’ll be creating it by first specifying the DbContextOptions with DbContextOptionsBuilder and then just passing that on to the constructor of your DbContext class instead. You’ll essentially just need the connection string and a few dependencies for this.

Solution

Through some googling and a bit of trials and errors, I’ve finally come up with this simple set of steps:

Time needed: 10 minutes

How to instantiate an Entity Framework Core database context using DbContextOptionsBuilder

  1. Add dependencies

    You’ll need to add these dependencies – and hence the NuGet packages “Microsoft.EntityFrameworkCore” and “Microsoft.EntityFrameworkCore.SqlServer“.

    Then, add your using statements, like in the example below:

    // EF dependencies:
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.SqlServer;

    // and of course, something like this: using YourNamespace.Data.Entities;

    Note – in newer versions of .NET Core CLI , you won’t be needing the Microsoft.EntityFrameworkCore.SqlServer reference there (you will still need the nuget package though!)

    Caveat: Tooling might be a bit “meh” here!

    Interestingly, in some versions of Visual Studio, Intellisense bugs out and tries to remove the usings. See this post for more information about that:
    How to access Entity Framework Core’s DbContext in an Azure Function?

    But that’s enough of that. Now…

  2. Configure your Database Context

    You’ll need to add a suitable constructor for our next step to your dbcontext class – somewhat like below:

    using Microsoft.EntityFrameworkCore;

    namespace DataLayer
    {
    public class ApplicationDbContext : DbContext
    {
    // entities etc omitted

    public ApplicationDbContext(DbContextOptions options) : base(options) { }

    }
    }

  3. Enough – show me the code!

    Okay – not too complicated or anything. See below for my example code:

    using Microsoft.EntityFrameworkCore;
    using System;

    namespace YourNamespace
    {
    public class YourClass
    {
    private string _connectionString = "Comes from your configuration file";

    public YourClass()
    {
    // In this example
    // "ApplicationDbContext" is my DbContext class
    var options = new DbContextOptionsBuilder<ApplicationDbContext>().UseSqlServer(_connectionString).Options;
    // With the options generated above, we can then just construct a new DbContext class

    using (var ctx = new ApplicationDbContext(options))
    {
    // Your code here
    }

    }
    }
    }

    Copy-paste it and give it a go!

  4. What’s next?

    Actually, there’s no step 3. It should be done with that! You just add whatever DB-querying code you might have inside the block where you’re using the context.

    This piece of code should successfully connect to a MS SQL Database, and perform whatever cool stuff it needs to do!


Any comments or questions, let me know in the comments-section below!

mm
4.3 23 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
most voted
newest oldest
Inline Feedbacks
View all comments