Search code examples
c#entity-frameworksqlite.net-coredatacontext

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

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