In one of my first attempts on using EntityFrameworkCore I quickly ran into the following error
This problem appears when your dbcontext is in a different project than your web project.

Unable to create an object of type ‘….DbContext’. Add an implementation of ‘IDesignTimeDbContextFactory’ to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

I fixed this by implementing the IDesignTimeDbContextFactory as follows:

    public class YourDbContextDesignTimeFactory : IDesignTimeDbContextFactory<YourDbContext>
    {
        public BuildMonitorDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<YourDbContext>();
            optionsBuilder.UseSqlServer(@"ConnectionStringGoesHere");

            return new YourDbContext(optionsBuilder.Options);
        }
    }

A better solution would be storing the connection string in your appsettings file.

        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
 
        var builder = new DbContextOptionsBuilder<YourDbContext>();
 
        var connectionString = configuration.GetConnectionString("YourDbContext");

The appsettings.json file would look something like

{
  "ConnectionStrings": {
    "YourDbContext": "ConnectionStringGoesHere"
  }
}
The following two tabs change content below.
I'm a software developer from Utrecht. Interested in DDD, continuous delivery, new technologies & frameworks.