'Unable to create an object of type 'MyContext'. For the different patterns supported at design time

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 'MyContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

i've added: var context = host.Services.GetRequiredService<MyContext>(); Also i've added private readonly DbContextOptions<MyContext> _opts; in my Post Class:

using (MyContext db = new MyContext(_opts))
 {
 db.Posts.Add(postData);
 db.SaveChanges();
 }

This how i added service:

.ConfigureServices((context, services) =>
                {
                    services.Configure<DataOptions>(opts =>
                        context.Configuration.GetSection(nameof(DataOptions)).Bind(opts));
                    services.AddDbContext<MyContext>((provider, builder) =>
                        builder.UseSqlite(provider.GetRequiredService<IOptions<DataOptions>>().Value.ConnectionString));

And this is my Context:

public sealed class MyContext : DbContext
    {
        private readonly DbContextOptions<MyContext> _options;

        public DbSet<PostData> Posts { get; set; }
        public DbSet<VoteData> Votes { get; set; }


        public MyContext(DbContextOptions<MyContext> options) : base(options)
        {
            _options = options;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlite("ConnectionString");
            }
        }

    }

I tried add-migration and has this error

What i do wrong?



Solution 1:[1]

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);            
    }
}

Solution 2:[2]

I came across this problem today. In my case, the SqlDbContext was in a separate ASP.Net Core 3.1 class library project, and I was trying to setup migrations using the dotnet CLI from that project's root folder. The main web application, which is the default project, contains the connection string configuration inside the appsettings.json and the startup configurations therefore I had to specify the startup project path using the -s switch as follows.

>dotnet ef migrations add initialcreation -s ..\MyWebApp\MyWebApp.csproj

-s, short for startup project, is a quick alternative to implementing IDesignTimeDbContextFactory when the DbContext is in a different project than the web application project.

Solution 3:[3]

The quick solution to the problem is to implement the default constructor in your context

 public MyContext() : base()
 {
 }

The problem with this solution is that you will have to enter the connection string in the 'OnConfiguring' function explicitly, which is not recommended

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlite("ConnectionString");
        }
 }

Solution 4:[4]

I've had same problem as You. Maybe it was not for a Console Application but error was the same. So i thought that it is worth to share with my answer. I was using NET Core 3.0 and to fix the problem I have to change the IHostBuilder into IWebHost and then everything was fine. The problem was in class Program.

public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });

into

public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .Build();

Solution 5:[5]

Kindly check your connection string also in appsetting,json.

Solution 6:[6]

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.

Solution 7:[7]

Ensure you have added DbContext to your services in Startup class

Solution 8:[8]

In my case, I had two startup project in my solution, so setting the project that has the connection string as the only startup project fixed the issue

Solution 9:[9]

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);
    }

Solution 10:[10]

Hade the same problem with NET Core 3.1.

Needed to add one more constructor too solev this. Why I do not know.

Never hade to do it in the past.

public DataContext()
{            
}

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

Solution 11:[11]

In my case problem was that I has multiple startup projects selected. selected one and it was fixed