Aleksej_Shherbak
Aleksej_Shherbak

Reputation: 3088

Error "Unable to create an object of type 'ApplicationDbContext'."

I'm working with Npgsql and Entity Framework. I'm trying to make new one migration but I have the error from the question title. I already have tried example from MS documentation.

So, my code is:

public class Program
{
    public static void Main(string[] args)
        => CreateHostBuilder(args).Build().Run();

    // EF Core uses this method at design time to access the DbContext
    public static IHostBuilder CreateHostBuilder(string[] args)
        => Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(
                webBuilder => webBuilder.UseStartup<Startup>());
}

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseNpgsql(Configuration.GetConnectionString("LalalaDb")));
    }
}

Where is the problem? How I can make a migration?

Update

This is my ApplicationDbContext.cs:

public class ApplicationDbContext : IdentityDbContext
{
    private readonly string _connectionString;

    public DbSet<Customer> Customers { get; set; }
    // and more DbSets are here ... 

    public ApplicationDbContext(IConfiguration configuration)
    {
        _connectionString = configuration.GetConnectionString("LalalaDb");
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql(_connectionString, b => b.MigrationsAssembly("EntityFrameworkProject"));
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

Upvotes: 0

Views: 786

Answers (3)

Juliana Polo
Juliana Polo

Reputation: 2287

I had the same issue and the problem in my project was that I had as StartUp Project the data layer. So I changed it to the project where the StartUp class was located and that was enough.

Upvotes: 0

Aleksej_Shherbak
Aleksej_Shherbak

Reputation: 3088

I have solved the issue! So, I just have Class library project. In the project I have:

  • ApplicationDbContext.cs (like in the question)
  • Folder with migrations.

And I just put Program.cs file with the following content:

public class Program
{
    public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            var envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile($"appsettings.{envName}.json")
                .Build();
            var builder = new DbContextOptionsBuilder<ApplicationDbContext>();
            var connectionString = configuration.GetConnectionString("LalalalDb");
            builder.UseNpgsql(connectionString);
            return new ApplicationDbContext(configuration);
        }
    }
}

Finally,

$ dotnet ef migrations add Lalalalalal - works!

P.S. Don't forget about appsettings.<Your ASPNETCORE_ENVIRONMENT>.json file.

Upvotes: 0

p4r1
p4r1

Reputation: 2650

You may want to look at the documentation for building your own DbContext class and the documentation for DbContext Creation for some additional considerations/best practices.

First thing I noticed is that your context class does not include a parameterless constructor or a constructor that takes in a DbContextOptions<T> instance, which is likely the cause for why migrations are not able to be created.

public class ApplicationDbContext : IdentityDbContext
{
    private readonly string _connectionString;

    public DbSet<Customer> Customers { get; set; }
    // and more DbSets are here ... 

    public ApplicationDbContext() : base()
    { }

    public ApplicationDbContext(IConfiguration configuration)
    {
        _connectionString = configuration.GetConnectionString("LalalaDb");
    }

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

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql(_connectionString, b => b.MigrationsAssembly("EntityFrameworkProject"));
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

Upvotes: 1

Related Questions