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

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


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


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.


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