Entity Framework Core logo

How to instantiate your DbContext outside your Data project?

This post was most recently updated on November 13th, 2019.

Reading Time: 3 minutes.

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 directly. For that, you’ll need your connection string and your entities – which you get access to from the database context object (DbContext).

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:

1. Add dependencies

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

Then, add your usings, 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:

But that’s enough of that. Now…

2. Show me the code!

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

using Microsoft.EntityFrameworkCore;
using System;
 
namespace YourNamespace
{
    public class YourClass
    {
        private string _connectionString = "This 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
            }
         }
    }
}

3. 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

Leave a Reply

avatar
5000
  Subscribe  
Notify of