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

Taifunov picture Taifunov · Sep 1, 2019 · Viewed 10.1k times · Source

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?

Answer

Steve picture Steve · Jun 25, 2020

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