I have ConsoleApplication on .NET Core and also i added my DbContext to dependencies, but howewer i have an error:
Unable to create an object of type \'My
I resolve this issue by this way:
public DbSet<PostData> Posts { get; set; }
public DbSet<VoteData> Votes { get; set; }
public MyContext(DbContextOptions options) : base(options) { Database.EnsureCreated(); }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(MyContext).Assembly);
}
I Resolved this by just adding a plain constructor to my Context
public class DataContext : DbContext
{
public DataContext()
{
}
public DataContext(DbContextOptions options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
if (!options.IsConfigured)
{
options.UseSqlServer("A FALLBACK CONNECTION STRING");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
This applies to ASP .NET or .NET console applications using .NET Core 3.1.
In my case it was ASPNET Core and I had the same reported problem after upgrading my application from 2.1 to 3.1. The answer provided by @Matt lead me to a solution that works and allows me to continue using the new Generic Host. The Web Host remains only for backward compatibility.
The documentation for Generic Host and Design-time DbContext Creation both state what needs to happen.
Your program.cs
must have a CreateHostBuilder
method with a signature exactly as documented. This is because the framework attempts to resolve it using Program.CreateHostBuilder()
. The signature must be:
public static IHostBuilder CreateHostBuilder(string[] args)
This is what caught me out, I initially had it named CreateWebHostBuilder
, a 2.1 convention; and then I didn't have the args
parameter defined. Fixing these two issues immediately resolved my add-migration ...
error.
The Design-time DbContext Creation documentation is quite helpful detailing how the framework attempts to resolve the DbContext
and explains why other suggestions here work the way they do, e.g. parameterless constructor.