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
- 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… - 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) { }
}
} - 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! - 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!
- How to fix PowerToys FancyZones in Windows 11? - September 24, 2024
- How to export the whole SSL (or TLS) certificate chain based on the original using PowerShell? - September 17, 2024
- How to solve keyboard shortcuts not working in Google Chrome on Windows? - September 10, 2024