skip to Main Content

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


  1. One of solutions, you create constructor like this

    public MssqlDbContext(IConfiguration configuration)
    {
        _connectionString = Configuration.GetConnectionString("DefaultConnection");
    }
    

    and override protected override void OnConfiguring(DbContextOptionsBuilder options)

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseMySql(_connectionString, ServerVersion.AutoDetect(connectionString));
    }
    
    Login or Signup to reply.
  2. 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:

    You can also tell the tools how to create your DbContext by implementing the Microsoft.EntityFrameworkCore.Design.IDesignTimeDbContextFactory interface: If a class implementing this interface is found in either the same project as the derived DbContext or in the application’s startup project, the tools bypass the other ways of creating the DbContext and use the design-time factory instead.

    Here’s a working example:

    using System.IO;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Design;
    using Microsoft.Extensions.Configuration;
    
    namespace MyProjectNamespace.EntityFrameworkCore;
    
    public class MyProjectDbContextFactory : IDesignTimeDbContextFactory<MyProjectDbContext>
    {
        public MyProjectDbContext CreateDbContext(string[] args)
        {
            var configuration = BuildConfiguration();
    
            var builder = new DbContextOptionsBuilder<MyProjectDbContext>()
                .UseSqlServer(configuration.GetConnectionString("Default"));
    
            return new MyProjectDbContext(builder.Options);
        }
    
        private static IConfigurationRoot BuildConfiguration()
        {
            // in some cases, .AddJsonFile("appsettings.json", optional: true); is appropriate
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false);
    
            return builder.Build();
        }
    }
    

    Add this file and build to validate its correctness. dotnet ef will pick up the IDesignTimeDbContextFactory and create your DbContext for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search