I am trying to set connect my SQL database to my .NET application but I am encountering an issue with Entity Framework Core, getting the following error:
dotnet ef migrations add InitialCreate
Build started...
Build succeeded.
Unable to create an object of type ‘AppDbContext’. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
This is my AppDbContext
code:
public class AppDbContext : DbContext
{
public DbSet<Barcode> Barcodes { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
}
I have configured my connection string in the appsettings.json
file, and my Startup.cs
registers the database context in the ConfigureServices
method as follows:
public void ConfigureServices(IServiceCollection services)
{
// Other service registrations...
var connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<AppDbContext>(options =>
{
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
});
}
What I’ve tried:
- Updated Entity Framework Core tools to the latest version
- Ensured that my connection string is correctly configured
- Verified project references and dependencies
- Checked that my
AppDbContext
class has a parameterless constructor
Any suggestions on how to resolve this problem would be greatly appreciated.
2
Answers
One of solutions, you create constructor like this
and override
protected override void OnConfiguring(DbContextOptionsBuilder options)
See here.
dotnet ef
runs design time processes that don’t use runtime app initialization to create the DbContext.For supported design-time patterns, you have options. I use
IDesignTimeDbContextFactory
: it’s discrete–no changes to the rest of your app, including the IServicesCollection–clear, and robust. MS Says:Here’s a working example:
Add this file and build to validate its correctness.
dotnet ef
will pick up the IDesignTimeDbContextFactory and create your DbContext for you.