How to add project implementation 'IDesignTimeDbContextFactory <DataContext>' to a project in asp.net-core-2.0

Here is the list of packages that I installed: Installed packages

I am using Entityframework 2.0 core. The first time I successfully created a database using the first migration of the entity code (add-migration and update-database command). Now when I update my entities and try to migrate, it gives me the following error.

Unable to create an object of type DataContext. Add the implementation of the 'IDesignTimeDbContextFactory' project or see https://go.microsoft.com/fwlink/?linkid=851728 for additional templates supported during development.

Here is my code ...

Program.cs

`public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build();` 

Startup.cs

 public Startup( IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices( IServiceCollection services) { // Repositories services.AddMvc(); services.AddDbContextPool<DataContext>( options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); //options => options.UseSqlServer(@"Server=LAPTOP-518D8067;Database=Gyanstack;Trusted_Connection=True;MultipleActiveResultSets=true")); services.AddCors(); services.AddScoped<ISectionRepository, SectionRepository>(); services.AddScoped(typeof(IEntityBaseRepository<>), typeof(EntityBaseRepository<>)); } 

DataContext.cs

  public class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options) : base(options) { } public DbSet<Section> Section { get; set; } public DbSet<SubSection> SubSection { get; set; } public DbSet<Article> Article { get; set; } public DbSet<Comment> Comment { get; set; } public DbSet<User> User { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.AddConfiguration(new SectionMap()); modelBuilder.AddConfiguration(new SubSectionMap()); modelBuilder.AddConfiguration(new ArticleMap()); modelBuilder.AddConfiguration(new CommentMap()); } } 
+8
c # entity-framework-core
source share
8 answers

Added Manish comment as an answer for formatting:

I created a class and implements IDesignTimeDbContext and it started working

 public class TemporaryDbContextFactory : IDesignTimeDbContextFactory<DataContext> { //////// public DataContext CreateDbContext(string[] args) { var builder = new DbContextOptionsBuilder<DataContext>(); IConfigurationRoot configuration = new ConfigurationBuilder() .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile("appsettings.json") .Build(); builder.UseSqlServer(configuration.GetConnectionString("Defa‌​ultConnection")); return new DataContext(builder.Options); } } 

EDIT: now deprecated. Microsoft updated its migration document at the end of September to show how to update, so you don't need this workaround.

As you can see from this problem that I raised in github , you move your DB initialization code to the main program, placing it between BuildWebHost () and .Run ()

It is relatively easy when you understand that you need to use the database context using var context = services.GetRequiredService<MyContext>(); in Main, and then everything works as expected. (although I still think DB initialization is a one-time initialization, not work with every program)

+9
source share

In 2.0 projects, move the call to SeedData.Initialize to the Main method of Program.cs:

 var host = BuildWebHost(args); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { SeedData.Initialize(services, "").Wait(); } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred seeding the DB."); } } host.Run(); 

Link: https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/#move-database-initialization-code

+1
source share

Just changed my Program.cs

from this

 public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } 

to that

 public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } 

Source: https://wildermuth.com/2017/07/06/Program-cs-in-ASP-NET-Core-2-0

+1
source share

The problem is to cut the db from Startup.Configure ... you can still do it with this work. Tested and works great

https://garywoodfine.com/how-to-seed-your-ef-core-database/

0
source share

It seems that EF 2.0 does not work with the "sample data" that remains from the old base project template. I managed to get rid of this error by simply commenting on the following line:

 SampleData.Initialize(app.ApplicationServices); 

I think,

 var context = serviceProvider.GetService<ApplicationDbContext>(); context.Database.Migrate(); 

accepts this error. I am not sure if this fix is ​​correct, but it works.

0
source share

This is due to the new .NET Core 2.0 initialization process, in which the configuration is handled differently (more details here ).

If you upgraded from 1.x, change your Program.cs and Startup.cs :

 public class Program { public static void Main(String[] args) { Program.BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(String[] args) => WebHost.CreateDefaultBuilder(args) .UseKestrel() .UseUrls("http://*:8000") .UseStartup<Startup>() .Build(); } public class Statup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } ........ } 

After this modification, your migrations should work, and there is no need to implement IDesignTimeDbContextFactory .

0
source share

I had the same issue on the latest .Net Core 2.0.3 . I have a separate project with dbContext implementation (from my IUnitOfWork user interface), and at first the migration worked fine. But after I implemented some other infrastructure, I have a similar error:

Unable to create object of type "TestCoreUnitOfWork". Add the implementation of 'IDesignTimeDbContextFactory' for the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional templates supported during development.

The proposed solution for implementing IDesignTimeDbContextFactory is fine, but I was wondering why the migration worked before? I spent several hours to find out which code change disrupted the migration. And, as it turned out, it was bootloader initialization, where I loaded all the referenced assemblies (via Assembly.Load () ) from my solution. After I changed this to a more traditional way with a direct call to all bootloaders, the migration started working again.

To summarize and answer the question, one of the possible causes of the migration error is using Assembly.Load () in StartUp.ConfigureServices () .

I hope this will be helpful to someone.

0
source share

I ran into this error when using Npgsql.EntityFrameworkCore.PostgreSQL, if that matters.

Whereas https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/#add-configuration-providers

I added this to BuildWebHost ()

 .ConfigureAppConfiguration((hostContext, config) => { // delete all default configuration providers config.Sources.Clear(); config.AddJsonFile("appsettings.json", optional: true); }) 

so bacame:

 public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .ConfigureAppConfiguration((hostContext, config) => { // delete all default configuration providers config.Sources.Clear(); config.AddJsonFile("appsettings.json", optional: true); }) .Build(); 

Now it works

0
source share

All Articles