Unable to create migrations after upgrading to ASP.NET Core 2.0
up vote
34
down vote
favorite
After upgrading to ASP.NET Core 2.0, I can't seem to create migrations anymore.
I'm getting
"An error occurred while calling method 'BuildWebHost' on class
'Program'. Continuing without the application service provider. Error:
One or more errors occurred. (Cannot open database "..." requested by
the login. The login failed. Login failed for user '...'"
and
"Unable to create an object of type 'MyContext'. Add an implementation
of 'IDesignTimeDbContextFactory' to the project, or see
https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns
supported at design time."
The command I previously ran was $ dotnet ef migrations add InitialCreate --startup-project "..Web"
(from the project/folder with the DBContext).
Connection string: "Server=(localdb)\mssqllocaldb;Database=database;Trusted_Connection=True;MultipleActiveResultSets=true"
This is my Program.cs
public class Program
public static void Main(string args)
BuildWebHost(args).Run();
public static IWebHost BuildWebHost(string args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
c# asp.net-core asp.net-core-mvc entity-framework-core asp.net-core-2.0
add a comment |
up vote
34
down vote
favorite
After upgrading to ASP.NET Core 2.0, I can't seem to create migrations anymore.
I'm getting
"An error occurred while calling method 'BuildWebHost' on class
'Program'. Continuing without the application service provider. Error:
One or more errors occurred. (Cannot open database "..." requested by
the login. The login failed. Login failed for user '...'"
and
"Unable to create an object of type 'MyContext'. Add an implementation
of 'IDesignTimeDbContextFactory' to the project, or see
https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns
supported at design time."
The command I previously ran was $ dotnet ef migrations add InitialCreate --startup-project "..Web"
(from the project/folder with the DBContext).
Connection string: "Server=(localdb)\mssqllocaldb;Database=database;Trusted_Connection=True;MultipleActiveResultSets=true"
This is my Program.cs
public class Program
public static void Main(string args)
BuildWebHost(args).Run();
public static IWebHost BuildWebHost(string args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
c# asp.net-core asp.net-core-mvc entity-framework-core asp.net-core-2.0
3
Possibly the problem is not in Program.cs. It is probably the use of an instruction to load seed data at the end of your Configure method: DbInitializer.Initialize (context); If you have that instruction, comment it: //DbInitializer.Initialize(context); Then run the Migration instructions to test. If the problem arises, then follow up on the DbInitializer.cs class.
– Miguel Torres C
Aug 20 '17 at 20:17
Is your MyContext class in another class library project?
– Orhun
Aug 22 '17 at 6:37
Same issue here, context is in other library. If id add an parameter less consturctor to the context, migrations are working, but with the same error: (An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Object reference not set to an instance of an object. )
– iBoonZ
Aug 26 '17 at 11:40
Did you get it resolved in the end?
– Konrad Viltersten
Sep 8 '17 at 11:19
@MiguelTorresC thanks for that comment. I commented out my Seeding Methods and Migrations began to work again. Thanks a ton !!!
– Amit Philips
Jul 12 at 2:20
add a comment |
up vote
34
down vote
favorite
up vote
34
down vote
favorite
After upgrading to ASP.NET Core 2.0, I can't seem to create migrations anymore.
I'm getting
"An error occurred while calling method 'BuildWebHost' on class
'Program'. Continuing without the application service provider. Error:
One or more errors occurred. (Cannot open database "..." requested by
the login. The login failed. Login failed for user '...'"
and
"Unable to create an object of type 'MyContext'. Add an implementation
of 'IDesignTimeDbContextFactory' to the project, or see
https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns
supported at design time."
The command I previously ran was $ dotnet ef migrations add InitialCreate --startup-project "..Web"
(from the project/folder with the DBContext).
Connection string: "Server=(localdb)\mssqllocaldb;Database=database;Trusted_Connection=True;MultipleActiveResultSets=true"
This is my Program.cs
public class Program
public static void Main(string args)
BuildWebHost(args).Run();
public static IWebHost BuildWebHost(string args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
c# asp.net-core asp.net-core-mvc entity-framework-core asp.net-core-2.0
After upgrading to ASP.NET Core 2.0, I can't seem to create migrations anymore.
I'm getting
"An error occurred while calling method 'BuildWebHost' on class
'Program'. Continuing without the application service provider. Error:
One or more errors occurred. (Cannot open database "..." requested by
the login. The login failed. Login failed for user '...'"
and
"Unable to create an object of type 'MyContext'. Add an implementation
of 'IDesignTimeDbContextFactory' to the project, or see
https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns
supported at design time."
The command I previously ran was $ dotnet ef migrations add InitialCreate --startup-project "..Web"
(from the project/folder with the DBContext).
Connection string: "Server=(localdb)\mssqllocaldb;Database=database;Trusted_Connection=True;MultipleActiveResultSets=true"
This is my Program.cs
public class Program
public static void Main(string args)
BuildWebHost(args).Run();
public static IWebHost BuildWebHost(string args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
c# asp.net-core asp.net-core-mvc entity-framework-core asp.net-core-2.0
c# asp.net-core asp.net-core-mvc entity-framework-core asp.net-core-2.0
edited Aug 20 '17 at 13:07
Itchydon
1,3761719
1,3761719
asked Aug 20 '17 at 13:01
runhum
200128
200128
3
Possibly the problem is not in Program.cs. It is probably the use of an instruction to load seed data at the end of your Configure method: DbInitializer.Initialize (context); If you have that instruction, comment it: //DbInitializer.Initialize(context); Then run the Migration instructions to test. If the problem arises, then follow up on the DbInitializer.cs class.
– Miguel Torres C
Aug 20 '17 at 20:17
Is your MyContext class in another class library project?
– Orhun
Aug 22 '17 at 6:37
Same issue here, context is in other library. If id add an parameter less consturctor to the context, migrations are working, but with the same error: (An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Object reference not set to an instance of an object. )
– iBoonZ
Aug 26 '17 at 11:40
Did you get it resolved in the end?
– Konrad Viltersten
Sep 8 '17 at 11:19
@MiguelTorresC thanks for that comment. I commented out my Seeding Methods and Migrations began to work again. Thanks a ton !!!
– Amit Philips
Jul 12 at 2:20
add a comment |
3
Possibly the problem is not in Program.cs. It is probably the use of an instruction to load seed data at the end of your Configure method: DbInitializer.Initialize (context); If you have that instruction, comment it: //DbInitializer.Initialize(context); Then run the Migration instructions to test. If the problem arises, then follow up on the DbInitializer.cs class.
– Miguel Torres C
Aug 20 '17 at 20:17
Is your MyContext class in another class library project?
– Orhun
Aug 22 '17 at 6:37
Same issue here, context is in other library. If id add an parameter less consturctor to the context, migrations are working, but with the same error: (An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Object reference not set to an instance of an object. )
– iBoonZ
Aug 26 '17 at 11:40
Did you get it resolved in the end?
– Konrad Viltersten
Sep 8 '17 at 11:19
@MiguelTorresC thanks for that comment. I commented out my Seeding Methods and Migrations began to work again. Thanks a ton !!!
– Amit Philips
Jul 12 at 2:20
3
3
Possibly the problem is not in Program.cs. It is probably the use of an instruction to load seed data at the end of your Configure method: DbInitializer.Initialize (context); If you have that instruction, comment it: //DbInitializer.Initialize(context); Then run the Migration instructions to test. If the problem arises, then follow up on the DbInitializer.cs class.
– Miguel Torres C
Aug 20 '17 at 20:17
Possibly the problem is not in Program.cs. It is probably the use of an instruction to load seed data at the end of your Configure method: DbInitializer.Initialize (context); If you have that instruction, comment it: //DbInitializer.Initialize(context); Then run the Migration instructions to test. If the problem arises, then follow up on the DbInitializer.cs class.
– Miguel Torres C
Aug 20 '17 at 20:17
Is your MyContext class in another class library project?
– Orhun
Aug 22 '17 at 6:37
Is your MyContext class in another class library project?
– Orhun
Aug 22 '17 at 6:37
Same issue here, context is in other library. If id add an parameter less consturctor to the context, migrations are working, but with the same error: (An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Object reference not set to an instance of an object. )
– iBoonZ
Aug 26 '17 at 11:40
Same issue here, context is in other library. If id add an parameter less consturctor to the context, migrations are working, but with the same error: (An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Object reference not set to an instance of an object. )
– iBoonZ
Aug 26 '17 at 11:40
Did you get it resolved in the end?
– Konrad Viltersten
Sep 8 '17 at 11:19
Did you get it resolved in the end?
– Konrad Viltersten
Sep 8 '17 at 11:19
@MiguelTorresC thanks for that comment. I commented out my Seeding Methods and Migrations began to work again. Thanks a ton !!!
– Amit Philips
Jul 12 at 2:20
@MiguelTorresC thanks for that comment. I commented out my Seeding Methods and Migrations began to work again. Thanks a ton !!!
– Amit Philips
Jul 12 at 2:20
add a comment |
17 Answers
17
active
oldest
votes
up vote
53
down vote
accepted
You can add a class that implements IDesignTimeDbContextFactory inside of your Web project.
Here is the sample code:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<CodingBlastDbContext>
public CodingBlastDbContext CreateDbContext(string args)
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<CodingBlastDbContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new CodingBlastDbContext(builder.Options);
Then, navigate to your Database project and run the following from command line:
dotnet ef migrations add InitialMigration -s ../Web/
dotnet ef database update -s ../Web/
-s stands for startup project and ../Web/ is the location of my web/startup project.
resource
2
I'm getting: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:UsersXXXDocumentsVisual Studio 2017ProjectsXXXsrcXXX.ApibinDebugnetcoreapp2.0appsettings.json'. My appsettings is in C:UsersXXXDocumentsVisual Studio 2017ProjectsXXXsrcXXX.Api.
– Reft
Sep 1 '17 at 19:37
Make sure you have the appsettings.json file set to copy local should fix the issue with it not being found
– DaImTo
Dec 8 '17 at 11:54
add a comment |
up vote
4
down vote
In the AppContext.cs besides AppContext class add another class:
// required when local database deleted
public class ToDoContextFactory : IDesignTimeDbContextFactory<AppContext>
public AppContext CreateDbContext(string args)
var builder = new DbContextOptionsBuilder<AppContext>();
builder.UseSqlServer("Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true");
return new AppContext(builder.Options);
This will solve your second problem:
"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project,
After that you will be able to add-migration Initial and execute it by running update-database command.
However if running these commands when there is no DataBase yet in your local SqlServer you will get the warning like your first error: "An error
occurred while calling method 'BuildWebHost' on class 'Program'... The
login failed. Login failed for user '...'"
But it is not error because migration will be created and it can be executed.
So just ignore this error for the first time, and latter since Db will exist it won't happen again.
add a comment |
up vote
4
down vote
No need for IDesignTimeDbContextFactory
.
Run
add-migration initial -verbose
that will reveal the details under
An error occurred while accessing the IWebHost on class 'Program'. Continuing without the application service provider.
warning, which is the root cause of the problem.
In my case, problem was, having ApplicationRole : IdentityRole<int>
and invoking services.AddIdentity<ApplicationUser, IdentityRole>()
which was causing below error
System.ArgumentException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole',
on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,
TKey,TUserClaim,TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type 'TRole'.
---> System.TypeLoadException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole',
on 'Microsoft.AspNetCore.Identity.UserStoreBase`8[TUser,TRole,TKey,TUserClaim,
TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type parameter 'TRole'.
This is weird, the commandadd-migration initial
threw the error no dbcontext found but when I ranadd-migration initial -verbose
it worked perfectly. I didn't make any code changes just changed the command. Any idea why?
– Ortho Home Defense
Oct 14 at 2:34
@OrthoHomeDefense well, that's really weird. I expect-verbose
to expose the underlying error details. Not really sure why it fixed an error.
– tchelidze
Oct 14 at 9:28
add a comment |
up vote
3
down vote
please verify that you have the reference
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" />
5
I'm using<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
which includes that reference. I tried also including the above, but no change.
– runhum
Aug 20 '17 at 16:19
add a comment |
up vote
3
down vote
You can try this solution from this discussion, which was inspired by this post.
public static IWebHost MigrateDatabase(this IWebHost webHost)
using (var scope = webHost.Services.CreateScope())
var services = scope.ServiceProvider;
try
var db = services.GetRequiredService<MyContext>();
db.Database.Migrate();
catch (Exception ex)
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while migrating the database.");
return webHost;
public static void Main(string args)
BuildWebHost(args)
.MigrateDatabase()
.Run();
2
I'm still getting: Add an implementation of 'IDesignTimeDbContextFactory<DatabaseContext>'......
– Reft
Sep 1 '17 at 19:50
add a comment |
up vote
3
down vote
Something that really helped me was this article: https://elanderson.net/2017/09/unable-to-create-an-object-of-type-applicationdbcontext-add-an-implementation-of-idesigntimedbcontextfactory/
The basic idea is that in the change over from .net core 1 to 2 all db initialization should be moved out of the StartUp.cs and into the Program.cs. Otherwise the EF tasks try and run your DB inits when doing tasks.
"There is a nice section in the official migration docs (https://docs.microsoft.com/en-us/ef/core/miscellaneous/1x-2x-upgrade) titled “Move database initialization code” which I seemed to have missed. So before you head down any rabbit holes like I did make sure this isn’t what is causing your need to add an implementation of IdesignTimeDbContextFactory."
Thanks, this helped me too.
– Sergey
Nov 13 '17 at 17:50
add a comment |
up vote
3
down vote
In my case, the cause of the problem was multiple startup projects. I have three projects in my solution: Mvc, Api, and Dal. DbContext and Migrations in the Dal project.
I had configured multiple startup projects. Both Mvc and Api projects were running when I clicked Start. But in this case I was getting this error.
"Unable to create an object of type 'MyContext'. 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 could successfully add migration after setting Mvc as the only startup project and selecting Dal in the Package Manager Console.
add a comment |
up vote
2
down vote
There's a problem with ef seeding db from Startup.Configure in 2.0 ... you can still do it with this work around. Tested and worked fine
https://garywoodfine.com/how-to-seed-your-ef-core-database/
add a comment |
up vote
2
down vote
In my case I got the problem because I had a method named SeedData.EnsurePopulated() being called on my Startup.cs file.
public class Startup
public Startup(IConfiguration configuration) => Configuration = configuration;
public IConfiguration Configuration get;
public void ConfigureServices(IServiceCollection services)
//
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
//
);
SeedData.EnsurePopulated(app);
The work of SeedData class is to add initial data to the database table. It's code is:
public static void EnsurePopulated(IApplicationBuilder app)
ApplicationDbContext context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>();
context.Database.Migrate();
if (!context.Products.Any())
context.Products.AddRange(
new Product
Name = "Kayak",
Description = "A boat for one person",
Category = "Watersports",
Price = 275
,
....
);
context.SaveChanges();
SOLUTION
Before doing migration simply comment out the calling of SeedData class in the Startup.cs file.
// SeedData.EnsurePopulated(app);
That solved my problem and hope your problem is also solved in the same way.
add a comment |
up vote
2
down vote
From
https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation
When you create a new ASP.NET Core 2.0 application, this hook is
included by default. In previous versions of EF Core and ASP.NET Core,
the tools try to invoke Startup.ConfigureServices directly in order to
obtain the application's service provider, but this pattern no longer
works correctly in ASP.NET Core 2.0 applications. If you are upgrading
an ASP.NET Core 1.x application to 2.0, you can modify your Program
class to follow the new pattern.
Add Factory in .Net Core 2.x
public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
public BloggingContext CreateDbContext(string args)
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");
return new BloggingContext(optionsBuilder.Options);
add a comment |
up vote
1
down vote
Previously, you configured the seed data in the Configure method in Startup.cs. It is now recommended that you use the Configure method only to set up the request pipeline. Application startup code belongs in the Main method.
The refactored Main method. Add the following references to the Program.cs:
using Microsoft.Extensions.DependencyInjection;
using MyProject.MyDbContextFolder;
public static void Main(string args)
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
var services = scope.ServiceProvider;
try
var context = services.GetRequiredService<MyDbConext>();
DbInitializer.Initialize(context);
catch (Exception ex)
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
host.Run();
add a comment |
up vote
1
down vote
A better solution :
If your startup project is an ASP.NET Core
app, the tools try to obtain the DbContext
object from the application's service provider.
The tool first try to obtain the service provider by invoking Program.BuildWebHost()
and accessing the IWebHost.Services
property.
add this method after Main Method in Program.cs
public static IWebHost BuildWebHost(string args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
add a comment |
up vote
0
down vote
I got the same issue since I was referring old- Microsoft.EntityFrameworkCore.Tools.DotNet
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
After upgrading to the newer version it got resolved
add a comment |
up vote
0
down vote
In main project's appsettings.json file, I had set 'Copy to Output directory' to "Copy always" and it worked.
add a comment |
up vote
0
down vote
Sample DB context class for .net core console applications
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System.IO;
namespace EmailServerConsole.Data
public class EmailDBContext : DbContext
public EmailDBContext(DbContextOptions<EmailDBContext> options) : base(options)
public DbSet<EmailQueue> EmailsQueue get; set;
public class ApplicationContextDbFactory : IDesignTimeDbContextFactory<EmailDBContext>
EmailDBContext IDesignTimeDbContextFactory<EmailDBContext>.CreateDbContext(string args)
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<EmailDBContext>();
var connectionString = configuration.GetConnectionString("connection_string");
builder.UseSqlServer(connectionString);
return new EmailDBContext(builder.Options);
While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find how to write a good answer very helpful. Please edit your answer.
– hellow
Sep 13 at 6:08
add a comment |
up vote
0
down vote
I had this problem and this solved By Set -> Web Application(Included Program.cs) Project to -> "Set as Startup Project"
Then run -> add-migration initial -verbose
in Package Manager Console
Set as Startup Project
add a comment |
up vote
-1
down vote
In my case this error occurred due to I remove MyDbContext from ConfigureServices because of some Design Patterns. Check that. In Startup.cs => ConfigureServices add these lines:
var connectionString = "Application Connection String!!!";
services.AddDbContext<MyDbContext>(c => c.UseSqlServer(connectionString));
add a comment |
17 Answers
17
active
oldest
votes
17 Answers
17
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
53
down vote
accepted
You can add a class that implements IDesignTimeDbContextFactory inside of your Web project.
Here is the sample code:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<CodingBlastDbContext>
public CodingBlastDbContext CreateDbContext(string args)
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<CodingBlastDbContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new CodingBlastDbContext(builder.Options);
Then, navigate to your Database project and run the following from command line:
dotnet ef migrations add InitialMigration -s ../Web/
dotnet ef database update -s ../Web/
-s stands for startup project and ../Web/ is the location of my web/startup project.
resource
2
I'm getting: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:UsersXXXDocumentsVisual Studio 2017ProjectsXXXsrcXXX.ApibinDebugnetcoreapp2.0appsettings.json'. My appsettings is in C:UsersXXXDocumentsVisual Studio 2017ProjectsXXXsrcXXX.Api.
– Reft
Sep 1 '17 at 19:37
Make sure you have the appsettings.json file set to copy local should fix the issue with it not being found
– DaImTo
Dec 8 '17 at 11:54
add a comment |
up vote
53
down vote
accepted
You can add a class that implements IDesignTimeDbContextFactory inside of your Web project.
Here is the sample code:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<CodingBlastDbContext>
public CodingBlastDbContext CreateDbContext(string args)
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<CodingBlastDbContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new CodingBlastDbContext(builder.Options);
Then, navigate to your Database project and run the following from command line:
dotnet ef migrations add InitialMigration -s ../Web/
dotnet ef database update -s ../Web/
-s stands for startup project and ../Web/ is the location of my web/startup project.
resource
2
I'm getting: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:UsersXXXDocumentsVisual Studio 2017ProjectsXXXsrcXXX.ApibinDebugnetcoreapp2.0appsettings.json'. My appsettings is in C:UsersXXXDocumentsVisual Studio 2017ProjectsXXXsrcXXX.Api.
– Reft
Sep 1 '17 at 19:37
Make sure you have the appsettings.json file set to copy local should fix the issue with it not being found
– DaImTo
Dec 8 '17 at 11:54
add a comment |
up vote
53
down vote
accepted
up vote
53
down vote
accepted
You can add a class that implements IDesignTimeDbContextFactory inside of your Web project.
Here is the sample code:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<CodingBlastDbContext>
public CodingBlastDbContext CreateDbContext(string args)
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<CodingBlastDbContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new CodingBlastDbContext(builder.Options);
Then, navigate to your Database project and run the following from command line:
dotnet ef migrations add InitialMigration -s ../Web/
dotnet ef database update -s ../Web/
-s stands for startup project and ../Web/ is the location of my web/startup project.
resource
You can add a class that implements IDesignTimeDbContextFactory inside of your Web project.
Here is the sample code:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<CodingBlastDbContext>
public CodingBlastDbContext CreateDbContext(string args)
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<CodingBlastDbContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new CodingBlastDbContext(builder.Options);
Then, navigate to your Database project and run the following from command line:
dotnet ef migrations add InitialMigration -s ../Web/
dotnet ef database update -s ../Web/
-s stands for startup project and ../Web/ is the location of my web/startup project.
resource
edited Jul 1 at 8:53
Mohamad Shiralizadeh
4,46943364
4,46943364
answered Aug 23 '17 at 7:28
jaaso
58136
58136
2
I'm getting: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:UsersXXXDocumentsVisual Studio 2017ProjectsXXXsrcXXX.ApibinDebugnetcoreapp2.0appsettings.json'. My appsettings is in C:UsersXXXDocumentsVisual Studio 2017ProjectsXXXsrcXXX.Api.
– Reft
Sep 1 '17 at 19:37
Make sure you have the appsettings.json file set to copy local should fix the issue with it not being found
– DaImTo
Dec 8 '17 at 11:54
add a comment |
2
I'm getting: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:UsersXXXDocumentsVisual Studio 2017ProjectsXXXsrcXXX.ApibinDebugnetcoreapp2.0appsettings.json'. My appsettings is in C:UsersXXXDocumentsVisual Studio 2017ProjectsXXXsrcXXX.Api.
– Reft
Sep 1 '17 at 19:37
Make sure you have the appsettings.json file set to copy local should fix the issue with it not being found
– DaImTo
Dec 8 '17 at 11:54
2
2
I'm getting: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:UsersXXXDocumentsVisual Studio 2017ProjectsXXXsrcXXX.ApibinDebugnetcoreapp2.0appsettings.json'. My appsettings is in C:UsersXXXDocumentsVisual Studio 2017ProjectsXXXsrcXXX.Api.
– Reft
Sep 1 '17 at 19:37
I'm getting: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:UsersXXXDocumentsVisual Studio 2017ProjectsXXXsrcXXX.ApibinDebugnetcoreapp2.0appsettings.json'. My appsettings is in C:UsersXXXDocumentsVisual Studio 2017ProjectsXXXsrcXXX.Api.
– Reft
Sep 1 '17 at 19:37
Make sure you have the appsettings.json file set to copy local should fix the issue with it not being found
– DaImTo
Dec 8 '17 at 11:54
Make sure you have the appsettings.json file set to copy local should fix the issue with it not being found
– DaImTo
Dec 8 '17 at 11:54
add a comment |
up vote
4
down vote
In the AppContext.cs besides AppContext class add another class:
// required when local database deleted
public class ToDoContextFactory : IDesignTimeDbContextFactory<AppContext>
public AppContext CreateDbContext(string args)
var builder = new DbContextOptionsBuilder<AppContext>();
builder.UseSqlServer("Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true");
return new AppContext(builder.Options);
This will solve your second problem:
"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project,
After that you will be able to add-migration Initial and execute it by running update-database command.
However if running these commands when there is no DataBase yet in your local SqlServer you will get the warning like your first error: "An error
occurred while calling method 'BuildWebHost' on class 'Program'... The
login failed. Login failed for user '...'"
But it is not error because migration will be created and it can be executed.
So just ignore this error for the first time, and latter since Db will exist it won't happen again.
add a comment |
up vote
4
down vote
In the AppContext.cs besides AppContext class add another class:
// required when local database deleted
public class ToDoContextFactory : IDesignTimeDbContextFactory<AppContext>
public AppContext CreateDbContext(string args)
var builder = new DbContextOptionsBuilder<AppContext>();
builder.UseSqlServer("Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true");
return new AppContext(builder.Options);
This will solve your second problem:
"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project,
After that you will be able to add-migration Initial and execute it by running update-database command.
However if running these commands when there is no DataBase yet in your local SqlServer you will get the warning like your first error: "An error
occurred while calling method 'BuildWebHost' on class 'Program'... The
login failed. Login failed for user '...'"
But it is not error because migration will be created and it can be executed.
So just ignore this error for the first time, and latter since Db will exist it won't happen again.
add a comment |
up vote
4
down vote
up vote
4
down vote
In the AppContext.cs besides AppContext class add another class:
// required when local database deleted
public class ToDoContextFactory : IDesignTimeDbContextFactory<AppContext>
public AppContext CreateDbContext(string args)
var builder = new DbContextOptionsBuilder<AppContext>();
builder.UseSqlServer("Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true");
return new AppContext(builder.Options);
This will solve your second problem:
"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project,
After that you will be able to add-migration Initial and execute it by running update-database command.
However if running these commands when there is no DataBase yet in your local SqlServer you will get the warning like your first error: "An error
occurred while calling method 'BuildWebHost' on class 'Program'... The
login failed. Login failed for user '...'"
But it is not error because migration will be created and it can be executed.
So just ignore this error for the first time, and latter since Db will exist it won't happen again.
In the AppContext.cs besides AppContext class add another class:
// required when local database deleted
public class ToDoContextFactory : IDesignTimeDbContextFactory<AppContext>
public AppContext CreateDbContext(string args)
var builder = new DbContextOptionsBuilder<AppContext>();
builder.UseSqlServer("Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true");
return new AppContext(builder.Options);
This will solve your second problem:
"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project,
After that you will be able to add-migration Initial and execute it by running update-database command.
However if running these commands when there is no DataBase yet in your local SqlServer you will get the warning like your first error: "An error
occurred while calling method 'BuildWebHost' on class 'Program'... The
login failed. Login failed for user '...'"
But it is not error because migration will be created and it can be executed.
So just ignore this error for the first time, and latter since Db will exist it won't happen again.
edited Sep 12 '17 at 13:26
answered Aug 21 '17 at 10:54
borisdj
5911721
5911721
add a comment |
add a comment |
up vote
4
down vote
No need for IDesignTimeDbContextFactory
.
Run
add-migration initial -verbose
that will reveal the details under
An error occurred while accessing the IWebHost on class 'Program'. Continuing without the application service provider.
warning, which is the root cause of the problem.
In my case, problem was, having ApplicationRole : IdentityRole<int>
and invoking services.AddIdentity<ApplicationUser, IdentityRole>()
which was causing below error
System.ArgumentException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole',
on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,
TKey,TUserClaim,TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type 'TRole'.
---> System.TypeLoadException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole',
on 'Microsoft.AspNetCore.Identity.UserStoreBase`8[TUser,TRole,TKey,TUserClaim,
TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type parameter 'TRole'.
This is weird, the commandadd-migration initial
threw the error no dbcontext found but when I ranadd-migration initial -verbose
it worked perfectly. I didn't make any code changes just changed the command. Any idea why?
– Ortho Home Defense
Oct 14 at 2:34
@OrthoHomeDefense well, that's really weird. I expect-verbose
to expose the underlying error details. Not really sure why it fixed an error.
– tchelidze
Oct 14 at 9:28
add a comment |
up vote
4
down vote
No need for IDesignTimeDbContextFactory
.
Run
add-migration initial -verbose
that will reveal the details under
An error occurred while accessing the IWebHost on class 'Program'. Continuing without the application service provider.
warning, which is the root cause of the problem.
In my case, problem was, having ApplicationRole : IdentityRole<int>
and invoking services.AddIdentity<ApplicationUser, IdentityRole>()
which was causing below error
System.ArgumentException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole',
on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,
TKey,TUserClaim,TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type 'TRole'.
---> System.TypeLoadException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole',
on 'Microsoft.AspNetCore.Identity.UserStoreBase`8[TUser,TRole,TKey,TUserClaim,
TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type parameter 'TRole'.
This is weird, the commandadd-migration initial
threw the error no dbcontext found but when I ranadd-migration initial -verbose
it worked perfectly. I didn't make any code changes just changed the command. Any idea why?
– Ortho Home Defense
Oct 14 at 2:34
@OrthoHomeDefense well, that's really weird. I expect-verbose
to expose the underlying error details. Not really sure why it fixed an error.
– tchelidze
Oct 14 at 9:28
add a comment |
up vote
4
down vote
up vote
4
down vote
No need for IDesignTimeDbContextFactory
.
Run
add-migration initial -verbose
that will reveal the details under
An error occurred while accessing the IWebHost on class 'Program'. Continuing without the application service provider.
warning, which is the root cause of the problem.
In my case, problem was, having ApplicationRole : IdentityRole<int>
and invoking services.AddIdentity<ApplicationUser, IdentityRole>()
which was causing below error
System.ArgumentException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole',
on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,
TKey,TUserClaim,TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type 'TRole'.
---> System.TypeLoadException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole',
on 'Microsoft.AspNetCore.Identity.UserStoreBase`8[TUser,TRole,TKey,TUserClaim,
TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type parameter 'TRole'.
No need for IDesignTimeDbContextFactory
.
Run
add-migration initial -verbose
that will reveal the details under
An error occurred while accessing the IWebHost on class 'Program'. Continuing without the application service provider.
warning, which is the root cause of the problem.
In my case, problem was, having ApplicationRole : IdentityRole<int>
and invoking services.AddIdentity<ApplicationUser, IdentityRole>()
which was causing below error
System.ArgumentException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole',
on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,
TKey,TUserClaim,TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type 'TRole'.
---> System.TypeLoadException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole',
on 'Microsoft.AspNetCore.Identity.UserStoreBase`8[TUser,TRole,TKey,TUserClaim,
TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type parameter 'TRole'.
edited Oct 31 at 8:39
answered Oct 5 at 18:24
tchelidze
5,05111432
5,05111432
This is weird, the commandadd-migration initial
threw the error no dbcontext found but when I ranadd-migration initial -verbose
it worked perfectly. I didn't make any code changes just changed the command. Any idea why?
– Ortho Home Defense
Oct 14 at 2:34
@OrthoHomeDefense well, that's really weird. I expect-verbose
to expose the underlying error details. Not really sure why it fixed an error.
– tchelidze
Oct 14 at 9:28
add a comment |
This is weird, the commandadd-migration initial
threw the error no dbcontext found but when I ranadd-migration initial -verbose
it worked perfectly. I didn't make any code changes just changed the command. Any idea why?
– Ortho Home Defense
Oct 14 at 2:34
@OrthoHomeDefense well, that's really weird. I expect-verbose
to expose the underlying error details. Not really sure why it fixed an error.
– tchelidze
Oct 14 at 9:28
This is weird, the command
add-migration initial
threw the error no dbcontext found but when I ran add-migration initial -verbose
it worked perfectly. I didn't make any code changes just changed the command. Any idea why?– Ortho Home Defense
Oct 14 at 2:34
This is weird, the command
add-migration initial
threw the error no dbcontext found but when I ran add-migration initial -verbose
it worked perfectly. I didn't make any code changes just changed the command. Any idea why?– Ortho Home Defense
Oct 14 at 2:34
@OrthoHomeDefense well, that's really weird. I expect
-verbose
to expose the underlying error details. Not really sure why it fixed an error.– tchelidze
Oct 14 at 9:28
@OrthoHomeDefense well, that's really weird. I expect
-verbose
to expose the underlying error details. Not really sure why it fixed an error.– tchelidze
Oct 14 at 9:28
add a comment |
up vote
3
down vote
please verify that you have the reference
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" />
5
I'm using<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
which includes that reference. I tried also including the above, but no change.
– runhum
Aug 20 '17 at 16:19
add a comment |
up vote
3
down vote
please verify that you have the reference
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" />
5
I'm using<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
which includes that reference. I tried also including the above, but no change.
– runhum
Aug 20 '17 at 16:19
add a comment |
up vote
3
down vote
up vote
3
down vote
please verify that you have the reference
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" />
please verify that you have the reference
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" />
answered Aug 20 '17 at 15:49
Vladmir
1,033712
1,033712
5
I'm using<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
which includes that reference. I tried also including the above, but no change.
– runhum
Aug 20 '17 at 16:19
add a comment |
5
I'm using<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
which includes that reference. I tried also including the above, but no change.
– runhum
Aug 20 '17 at 16:19
5
5
I'm using
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
which includes that reference. I tried also including the above, but no change.– runhum
Aug 20 '17 at 16:19
I'm using
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
which includes that reference. I tried also including the above, but no change.– runhum
Aug 20 '17 at 16:19
add a comment |
up vote
3
down vote
You can try this solution from this discussion, which was inspired by this post.
public static IWebHost MigrateDatabase(this IWebHost webHost)
using (var scope = webHost.Services.CreateScope())
var services = scope.ServiceProvider;
try
var db = services.GetRequiredService<MyContext>();
db.Database.Migrate();
catch (Exception ex)
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while migrating the database.");
return webHost;
public static void Main(string args)
BuildWebHost(args)
.MigrateDatabase()
.Run();
2
I'm still getting: Add an implementation of 'IDesignTimeDbContextFactory<DatabaseContext>'......
– Reft
Sep 1 '17 at 19:50
add a comment |
up vote
3
down vote
You can try this solution from this discussion, which was inspired by this post.
public static IWebHost MigrateDatabase(this IWebHost webHost)
using (var scope = webHost.Services.CreateScope())
var services = scope.ServiceProvider;
try
var db = services.GetRequiredService<MyContext>();
db.Database.Migrate();
catch (Exception ex)
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while migrating the database.");
return webHost;
public static void Main(string args)
BuildWebHost(args)
.MigrateDatabase()
.Run();
2
I'm still getting: Add an implementation of 'IDesignTimeDbContextFactory<DatabaseContext>'......
– Reft
Sep 1 '17 at 19:50
add a comment |
up vote
3
down vote
up vote
3
down vote
You can try this solution from this discussion, which was inspired by this post.
public static IWebHost MigrateDatabase(this IWebHost webHost)
using (var scope = webHost.Services.CreateScope())
var services = scope.ServiceProvider;
try
var db = services.GetRequiredService<MyContext>();
db.Database.Migrate();
catch (Exception ex)
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while migrating the database.");
return webHost;
public static void Main(string args)
BuildWebHost(args)
.MigrateDatabase()
.Run();
You can try this solution from this discussion, which was inspired by this post.
public static IWebHost MigrateDatabase(this IWebHost webHost)
using (var scope = webHost.Services.CreateScope())
var services = scope.ServiceProvider;
try
var db = services.GetRequiredService<MyContext>();
db.Database.Migrate();
catch (Exception ex)
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while migrating the database.");
return webHost;
public static void Main(string args)
BuildWebHost(args)
.MigrateDatabase()
.Run();
edited Aug 21 '17 at 6:44
answered Aug 20 '17 at 18:27
user2771704
3,54332734
3,54332734
2
I'm still getting: Add an implementation of 'IDesignTimeDbContextFactory<DatabaseContext>'......
– Reft
Sep 1 '17 at 19:50
add a comment |
2
I'm still getting: Add an implementation of 'IDesignTimeDbContextFactory<DatabaseContext>'......
– Reft
Sep 1 '17 at 19:50
2
2
I'm still getting: Add an implementation of 'IDesignTimeDbContextFactory<DatabaseContext>'......
– Reft
Sep 1 '17 at 19:50
I'm still getting: Add an implementation of 'IDesignTimeDbContextFactory<DatabaseContext>'......
– Reft
Sep 1 '17 at 19:50
add a comment |
up vote
3
down vote
Something that really helped me was this article: https://elanderson.net/2017/09/unable-to-create-an-object-of-type-applicationdbcontext-add-an-implementation-of-idesigntimedbcontextfactory/
The basic idea is that in the change over from .net core 1 to 2 all db initialization should be moved out of the StartUp.cs and into the Program.cs. Otherwise the EF tasks try and run your DB inits when doing tasks.
"There is a nice section in the official migration docs (https://docs.microsoft.com/en-us/ef/core/miscellaneous/1x-2x-upgrade) titled “Move database initialization code” which I seemed to have missed. So before you head down any rabbit holes like I did make sure this isn’t what is causing your need to add an implementation of IdesignTimeDbContextFactory."
Thanks, this helped me too.
– Sergey
Nov 13 '17 at 17:50
add a comment |
up vote
3
down vote
Something that really helped me was this article: https://elanderson.net/2017/09/unable-to-create-an-object-of-type-applicationdbcontext-add-an-implementation-of-idesigntimedbcontextfactory/
The basic idea is that in the change over from .net core 1 to 2 all db initialization should be moved out of the StartUp.cs and into the Program.cs. Otherwise the EF tasks try and run your DB inits when doing tasks.
"There is a nice section in the official migration docs (https://docs.microsoft.com/en-us/ef/core/miscellaneous/1x-2x-upgrade) titled “Move database initialization code” which I seemed to have missed. So before you head down any rabbit holes like I did make sure this isn’t what is causing your need to add an implementation of IdesignTimeDbContextFactory."
Thanks, this helped me too.
– Sergey
Nov 13 '17 at 17:50
add a comment |
up vote
3
down vote
up vote
3
down vote
Something that really helped me was this article: https://elanderson.net/2017/09/unable-to-create-an-object-of-type-applicationdbcontext-add-an-implementation-of-idesigntimedbcontextfactory/
The basic idea is that in the change over from .net core 1 to 2 all db initialization should be moved out of the StartUp.cs and into the Program.cs. Otherwise the EF tasks try and run your DB inits when doing tasks.
"There is a nice section in the official migration docs (https://docs.microsoft.com/en-us/ef/core/miscellaneous/1x-2x-upgrade) titled “Move database initialization code” which I seemed to have missed. So before you head down any rabbit holes like I did make sure this isn’t what is causing your need to add an implementation of IdesignTimeDbContextFactory."
Something that really helped me was this article: https://elanderson.net/2017/09/unable-to-create-an-object-of-type-applicationdbcontext-add-an-implementation-of-idesigntimedbcontextfactory/
The basic idea is that in the change over from .net core 1 to 2 all db initialization should be moved out of the StartUp.cs and into the Program.cs. Otherwise the EF tasks try and run your DB inits when doing tasks.
"There is a nice section in the official migration docs (https://docs.microsoft.com/en-us/ef/core/miscellaneous/1x-2x-upgrade) titled “Move database initialization code” which I seemed to have missed. So before you head down any rabbit holes like I did make sure this isn’t what is causing your need to add an implementation of IdesignTimeDbContextFactory."
edited Oct 26 '17 at 2:46
answered Oct 26 '17 at 2:35
Rtype
580924
580924
Thanks, this helped me too.
– Sergey
Nov 13 '17 at 17:50
add a comment |
Thanks, this helped me too.
– Sergey
Nov 13 '17 at 17:50
Thanks, this helped me too.
– Sergey
Nov 13 '17 at 17:50
Thanks, this helped me too.
– Sergey
Nov 13 '17 at 17:50
add a comment |
up vote
3
down vote
In my case, the cause of the problem was multiple startup projects. I have three projects in my solution: Mvc, Api, and Dal. DbContext and Migrations in the Dal project.
I had configured multiple startup projects. Both Mvc and Api projects were running when I clicked Start. But in this case I was getting this error.
"Unable to create an object of type 'MyContext'. 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 could successfully add migration after setting Mvc as the only startup project and selecting Dal in the Package Manager Console.
add a comment |
up vote
3
down vote
In my case, the cause of the problem was multiple startup projects. I have three projects in my solution: Mvc, Api, and Dal. DbContext and Migrations in the Dal project.
I had configured multiple startup projects. Both Mvc and Api projects were running when I clicked Start. But in this case I was getting this error.
"Unable to create an object of type 'MyContext'. 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 could successfully add migration after setting Mvc as the only startup project and selecting Dal in the Package Manager Console.
add a comment |
up vote
3
down vote
up vote
3
down vote
In my case, the cause of the problem was multiple startup projects. I have three projects in my solution: Mvc, Api, and Dal. DbContext and Migrations in the Dal project.
I had configured multiple startup projects. Both Mvc and Api projects were running when I clicked Start. But in this case I was getting this error.
"Unable to create an object of type 'MyContext'. 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 could successfully add migration after setting Mvc as the only startup project and selecting Dal in the Package Manager Console.
In my case, the cause of the problem was multiple startup projects. I have three projects in my solution: Mvc, Api, and Dal. DbContext and Migrations in the Dal project.
I had configured multiple startup projects. Both Mvc and Api projects were running when I clicked Start. But in this case I was getting this error.
"Unable to create an object of type 'MyContext'. 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 could successfully add migration after setting Mvc as the only startup project and selecting Dal in the Package Manager Console.
answered Jun 21 at 11:12
Gürol Mehmet Cetin
312
312
add a comment |
add a comment |
up vote
2
down vote
There's a problem with ef seeding db from Startup.Configure in 2.0 ... you can still do it with this work around. Tested and worked fine
https://garywoodfine.com/how-to-seed-your-ef-core-database/
add a comment |
up vote
2
down vote
There's a problem with ef seeding db from Startup.Configure in 2.0 ... you can still do it with this work around. Tested and worked fine
https://garywoodfine.com/how-to-seed-your-ef-core-database/
add a comment |
up vote
2
down vote
up vote
2
down vote
There's a problem with ef seeding db from Startup.Configure in 2.0 ... you can still do it with this work around. Tested and worked fine
https://garywoodfine.com/how-to-seed-your-ef-core-database/
There's a problem with ef seeding db from Startup.Configure in 2.0 ... you can still do it with this work around. Tested and worked fine
https://garywoodfine.com/how-to-seed-your-ef-core-database/
answered Sep 9 '17 at 18:02
Nick G.
9114
9114
add a comment |
add a comment |
up vote
2
down vote
In my case I got the problem because I had a method named SeedData.EnsurePopulated() being called on my Startup.cs file.
public class Startup
public Startup(IConfiguration configuration) => Configuration = configuration;
public IConfiguration Configuration get;
public void ConfigureServices(IServiceCollection services)
//
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
//
);
SeedData.EnsurePopulated(app);
The work of SeedData class is to add initial data to the database table. It's code is:
public static void EnsurePopulated(IApplicationBuilder app)
ApplicationDbContext context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>();
context.Database.Migrate();
if (!context.Products.Any())
context.Products.AddRange(
new Product
Name = "Kayak",
Description = "A boat for one person",
Category = "Watersports",
Price = 275
,
....
);
context.SaveChanges();
SOLUTION
Before doing migration simply comment out the calling of SeedData class in the Startup.cs file.
// SeedData.EnsurePopulated(app);
That solved my problem and hope your problem is also solved in the same way.
add a comment |
up vote
2
down vote
In my case I got the problem because I had a method named SeedData.EnsurePopulated() being called on my Startup.cs file.
public class Startup
public Startup(IConfiguration configuration) => Configuration = configuration;
public IConfiguration Configuration get;
public void ConfigureServices(IServiceCollection services)
//
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
//
);
SeedData.EnsurePopulated(app);
The work of SeedData class is to add initial data to the database table. It's code is:
public static void EnsurePopulated(IApplicationBuilder app)
ApplicationDbContext context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>();
context.Database.Migrate();
if (!context.Products.Any())
context.Products.AddRange(
new Product
Name = "Kayak",
Description = "A boat for one person",
Category = "Watersports",
Price = 275
,
....
);
context.SaveChanges();
SOLUTION
Before doing migration simply comment out the calling of SeedData class in the Startup.cs file.
// SeedData.EnsurePopulated(app);
That solved my problem and hope your problem is also solved in the same way.
add a comment |
up vote
2
down vote
up vote
2
down vote
In my case I got the problem because I had a method named SeedData.EnsurePopulated() being called on my Startup.cs file.
public class Startup
public Startup(IConfiguration configuration) => Configuration = configuration;
public IConfiguration Configuration get;
public void ConfigureServices(IServiceCollection services)
//
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
//
);
SeedData.EnsurePopulated(app);
The work of SeedData class is to add initial data to the database table. It's code is:
public static void EnsurePopulated(IApplicationBuilder app)
ApplicationDbContext context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>();
context.Database.Migrate();
if (!context.Products.Any())
context.Products.AddRange(
new Product
Name = "Kayak",
Description = "A boat for one person",
Category = "Watersports",
Price = 275
,
....
);
context.SaveChanges();
SOLUTION
Before doing migration simply comment out the calling of SeedData class in the Startup.cs file.
// SeedData.EnsurePopulated(app);
That solved my problem and hope your problem is also solved in the same way.
In my case I got the problem because I had a method named SeedData.EnsurePopulated() being called on my Startup.cs file.
public class Startup
public Startup(IConfiguration configuration) => Configuration = configuration;
public IConfiguration Configuration get;
public void ConfigureServices(IServiceCollection services)
//
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
//
);
SeedData.EnsurePopulated(app);
The work of SeedData class is to add initial data to the database table. It's code is:
public static void EnsurePopulated(IApplicationBuilder app)
ApplicationDbContext context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>();
context.Database.Migrate();
if (!context.Products.Any())
context.Products.AddRange(
new Product
Name = "Kayak",
Description = "A boat for one person",
Category = "Watersports",
Price = 275
,
....
);
context.SaveChanges();
SOLUTION
Before doing migration simply comment out the calling of SeedData class in the Startup.cs file.
// SeedData.EnsurePopulated(app);
That solved my problem and hope your problem is also solved in the same way.
answered Mar 9 at 14:04
yogihosting
1,86311430
1,86311430
add a comment |
add a comment |
up vote
2
down vote
From
https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation
When you create a new ASP.NET Core 2.0 application, this hook is
included by default. In previous versions of EF Core and ASP.NET Core,
the tools try to invoke Startup.ConfigureServices directly in order to
obtain the application's service provider, but this pattern no longer
works correctly in ASP.NET Core 2.0 applications. If you are upgrading
an ASP.NET Core 1.x application to 2.0, you can modify your Program
class to follow the new pattern.
Add Factory in .Net Core 2.x
public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
public BloggingContext CreateDbContext(string args)
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");
return new BloggingContext(optionsBuilder.Options);
add a comment |
up vote
2
down vote
From
https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation
When you create a new ASP.NET Core 2.0 application, this hook is
included by default. In previous versions of EF Core and ASP.NET Core,
the tools try to invoke Startup.ConfigureServices directly in order to
obtain the application's service provider, but this pattern no longer
works correctly in ASP.NET Core 2.0 applications. If you are upgrading
an ASP.NET Core 1.x application to 2.0, you can modify your Program
class to follow the new pattern.
Add Factory in .Net Core 2.x
public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
public BloggingContext CreateDbContext(string args)
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");
return new BloggingContext(optionsBuilder.Options);
add a comment |
up vote
2
down vote
up vote
2
down vote
From
https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation
When you create a new ASP.NET Core 2.0 application, this hook is
included by default. In previous versions of EF Core and ASP.NET Core,
the tools try to invoke Startup.ConfigureServices directly in order to
obtain the application's service provider, but this pattern no longer
works correctly in ASP.NET Core 2.0 applications. If you are upgrading
an ASP.NET Core 1.x application to 2.0, you can modify your Program
class to follow the new pattern.
Add Factory in .Net Core 2.x
public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
public BloggingContext CreateDbContext(string args)
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");
return new BloggingContext(optionsBuilder.Options);
From
https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation
When you create a new ASP.NET Core 2.0 application, this hook is
included by default. In previous versions of EF Core and ASP.NET Core,
the tools try to invoke Startup.ConfigureServices directly in order to
obtain the application's service provider, but this pattern no longer
works correctly in ASP.NET Core 2.0 applications. If you are upgrading
an ASP.NET Core 1.x application to 2.0, you can modify your Program
class to follow the new pattern.
Add Factory in .Net Core 2.x
public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
public BloggingContext CreateDbContext(string args)
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");
return new BloggingContext(optionsBuilder.Options);
answered Aug 24 at 11:31
Anton Swanevelder
10112
10112
add a comment |
add a comment |
up vote
1
down vote
Previously, you configured the seed data in the Configure method in Startup.cs. It is now recommended that you use the Configure method only to set up the request pipeline. Application startup code belongs in the Main method.
The refactored Main method. Add the following references to the Program.cs:
using Microsoft.Extensions.DependencyInjection;
using MyProject.MyDbContextFolder;
public static void Main(string args)
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
var services = scope.ServiceProvider;
try
var context = services.GetRequiredService<MyDbConext>();
DbInitializer.Initialize(context);
catch (Exception ex)
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
host.Run();
add a comment |
up vote
1
down vote
Previously, you configured the seed data in the Configure method in Startup.cs. It is now recommended that you use the Configure method only to set up the request pipeline. Application startup code belongs in the Main method.
The refactored Main method. Add the following references to the Program.cs:
using Microsoft.Extensions.DependencyInjection;
using MyProject.MyDbContextFolder;
public static void Main(string args)
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
var services = scope.ServiceProvider;
try
var context = services.GetRequiredService<MyDbConext>();
DbInitializer.Initialize(context);
catch (Exception ex)
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
host.Run();
add a comment |
up vote
1
down vote
up vote
1
down vote
Previously, you configured the seed data in the Configure method in Startup.cs. It is now recommended that you use the Configure method only to set up the request pipeline. Application startup code belongs in the Main method.
The refactored Main method. Add the following references to the Program.cs:
using Microsoft.Extensions.DependencyInjection;
using MyProject.MyDbContextFolder;
public static void Main(string args)
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
var services = scope.ServiceProvider;
try
var context = services.GetRequiredService<MyDbConext>();
DbInitializer.Initialize(context);
catch (Exception ex)
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
host.Run();
Previously, you configured the seed data in the Configure method in Startup.cs. It is now recommended that you use the Configure method only to set up the request pipeline. Application startup code belongs in the Main method.
The refactored Main method. Add the following references to the Program.cs:
using Microsoft.Extensions.DependencyInjection;
using MyProject.MyDbContextFolder;
public static void Main(string args)
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
var services = scope.ServiceProvider;
try
var context = services.GetRequiredService<MyDbConext>();
DbInitializer.Initialize(context);
catch (Exception ex)
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
host.Run();
public static void Main(string args)
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
var services = scope.ServiceProvider;
try
var context = services.GetRequiredService<MyDbConext>();
DbInitializer.Initialize(context);
catch (Exception ex)
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
host.Run();
public static void Main(string args)
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
var services = scope.ServiceProvider;
try
var context = services.GetRequiredService<MyDbConext>();
DbInitializer.Initialize(context);
catch (Exception ex)
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
host.Run();
edited Aug 20 '17 at 21:36
answered Aug 20 '17 at 21:28
Miguel Torres C
30134
30134
add a comment |
add a comment |
up vote
1
down vote
A better solution :
If your startup project is an ASP.NET Core
app, the tools try to obtain the DbContext
object from the application's service provider.
The tool first try to obtain the service provider by invoking Program.BuildWebHost()
and accessing the IWebHost.Services
property.
add this method after Main Method in Program.cs
public static IWebHost BuildWebHost(string args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
add a comment |
up vote
1
down vote
A better solution :
If your startup project is an ASP.NET Core
app, the tools try to obtain the DbContext
object from the application's service provider.
The tool first try to obtain the service provider by invoking Program.BuildWebHost()
and accessing the IWebHost.Services
property.
add this method after Main Method in Program.cs
public static IWebHost BuildWebHost(string args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
add a comment |
up vote
1
down vote
up vote
1
down vote
A better solution :
If your startup project is an ASP.NET Core
app, the tools try to obtain the DbContext
object from the application's service provider.
The tool first try to obtain the service provider by invoking Program.BuildWebHost()
and accessing the IWebHost.Services
property.
add this method after Main Method in Program.cs
public static IWebHost BuildWebHost(string args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
A better solution :
If your startup project is an ASP.NET Core
app, the tools try to obtain the DbContext
object from the application's service provider.
The tool first try to obtain the service provider by invoking Program.BuildWebHost()
and accessing the IWebHost.Services
property.
add this method after Main Method in Program.cs
public static IWebHost BuildWebHost(string args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
answered Feb 7 at 9:15
Ali Bayat
1,31122324
1,31122324
add a comment |
add a comment |
up vote
0
down vote
I got the same issue since I was referring old- Microsoft.EntityFrameworkCore.Tools.DotNet
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
After upgrading to the newer version it got resolved
add a comment |
up vote
0
down vote
I got the same issue since I was referring old- Microsoft.EntityFrameworkCore.Tools.DotNet
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
After upgrading to the newer version it got resolved
add a comment |
up vote
0
down vote
up vote
0
down vote
I got the same issue since I was referring old- Microsoft.EntityFrameworkCore.Tools.DotNet
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
After upgrading to the newer version it got resolved
I got the same issue since I was referring old- Microsoft.EntityFrameworkCore.Tools.DotNet
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
After upgrading to the newer version it got resolved
answered Jun 10 at 10:01
vinayak hegde
9871313
9871313
add a comment |
add a comment |
up vote
0
down vote
In main project's appsettings.json file, I had set 'Copy to Output directory' to "Copy always" and it worked.
add a comment |
up vote
0
down vote
In main project's appsettings.json file, I had set 'Copy to Output directory' to "Copy always" and it worked.
add a comment |
up vote
0
down vote
up vote
0
down vote
In main project's appsettings.json file, I had set 'Copy to Output directory' to "Copy always" and it worked.
In main project's appsettings.json file, I had set 'Copy to Output directory' to "Copy always" and it worked.
answered Jul 9 at 6:54
geet
312
312
add a comment |
add a comment |
up vote
0
down vote
Sample DB context class for .net core console applications
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System.IO;
namespace EmailServerConsole.Data
public class EmailDBContext : DbContext
public EmailDBContext(DbContextOptions<EmailDBContext> options) : base(options)
public DbSet<EmailQueue> EmailsQueue get; set;
public class ApplicationContextDbFactory : IDesignTimeDbContextFactory<EmailDBContext>
EmailDBContext IDesignTimeDbContextFactory<EmailDBContext>.CreateDbContext(string args)
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<EmailDBContext>();
var connectionString = configuration.GetConnectionString("connection_string");
builder.UseSqlServer(connectionString);
return new EmailDBContext(builder.Options);
While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find how to write a good answer very helpful. Please edit your answer.
– hellow
Sep 13 at 6:08
add a comment |
up vote
0
down vote
Sample DB context class for .net core console applications
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System.IO;
namespace EmailServerConsole.Data
public class EmailDBContext : DbContext
public EmailDBContext(DbContextOptions<EmailDBContext> options) : base(options)
public DbSet<EmailQueue> EmailsQueue get; set;
public class ApplicationContextDbFactory : IDesignTimeDbContextFactory<EmailDBContext>
EmailDBContext IDesignTimeDbContextFactory<EmailDBContext>.CreateDbContext(string args)
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<EmailDBContext>();
var connectionString = configuration.GetConnectionString("connection_string");
builder.UseSqlServer(connectionString);
return new EmailDBContext(builder.Options);
While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find how to write a good answer very helpful. Please edit your answer.
– hellow
Sep 13 at 6:08
add a comment |
up vote
0
down vote
up vote
0
down vote
Sample DB context class for .net core console applications
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System.IO;
namespace EmailServerConsole.Data
public class EmailDBContext : DbContext
public EmailDBContext(DbContextOptions<EmailDBContext> options) : base(options)
public DbSet<EmailQueue> EmailsQueue get; set;
public class ApplicationContextDbFactory : IDesignTimeDbContextFactory<EmailDBContext>
EmailDBContext IDesignTimeDbContextFactory<EmailDBContext>.CreateDbContext(string args)
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<EmailDBContext>();
var connectionString = configuration.GetConnectionString("connection_string");
builder.UseSqlServer(connectionString);
return new EmailDBContext(builder.Options);
Sample DB context class for .net core console applications
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System.IO;
namespace EmailServerConsole.Data
public class EmailDBContext : DbContext
public EmailDBContext(DbContextOptions<EmailDBContext> options) : base(options)
public DbSet<EmailQueue> EmailsQueue get; set;
public class ApplicationContextDbFactory : IDesignTimeDbContextFactory<EmailDBContext>
EmailDBContext IDesignTimeDbContextFactory<EmailDBContext>.CreateDbContext(string args)
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<EmailDBContext>();
var connectionString = configuration.GetConnectionString("connection_string");
builder.UseSqlServer(connectionString);
return new EmailDBContext(builder.Options);
edited Sep 13 at 6:08
hellow
4,05122041
4,05122041
answered Sep 13 at 5:30
Isanka Thalagala
1219
1219
While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find how to write a good answer very helpful. Please edit your answer.
– hellow
Sep 13 at 6:08
add a comment |
While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find how to write a good answer very helpful. Please edit your answer.
– hellow
Sep 13 at 6:08
While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find how to write a good answer very helpful. Please edit your answer.
– hellow
Sep 13 at 6:08
While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find how to write a good answer very helpful. Please edit your answer.
– hellow
Sep 13 at 6:08
add a comment |
up vote
0
down vote
I had this problem and this solved By Set -> Web Application(Included Program.cs) Project to -> "Set as Startup Project"
Then run -> add-migration initial -verbose
in Package Manager Console
Set as Startup Project
add a comment |
up vote
0
down vote
I had this problem and this solved By Set -> Web Application(Included Program.cs) Project to -> "Set as Startup Project"
Then run -> add-migration initial -verbose
in Package Manager Console
Set as Startup Project
add a comment |
up vote
0
down vote
up vote
0
down vote
I had this problem and this solved By Set -> Web Application(Included Program.cs) Project to -> "Set as Startup Project"
Then run -> add-migration initial -verbose
in Package Manager Console
Set as Startup Project
I had this problem and this solved By Set -> Web Application(Included Program.cs) Project to -> "Set as Startup Project"
Then run -> add-migration initial -verbose
in Package Manager Console
Set as Startup Project
answered Nov 7 at 11:22
Ali Ahmadi
11
11
add a comment |
add a comment |
up vote
-1
down vote
In my case this error occurred due to I remove MyDbContext from ConfigureServices because of some Design Patterns. Check that. In Startup.cs => ConfigureServices add these lines:
var connectionString = "Application Connection String!!!";
services.AddDbContext<MyDbContext>(c => c.UseSqlServer(connectionString));
add a comment |
up vote
-1
down vote
In my case this error occurred due to I remove MyDbContext from ConfigureServices because of some Design Patterns. Check that. In Startup.cs => ConfigureServices add these lines:
var connectionString = "Application Connection String!!!";
services.AddDbContext<MyDbContext>(c => c.UseSqlServer(connectionString));
add a comment |
up vote
-1
down vote
up vote
-1
down vote
In my case this error occurred due to I remove MyDbContext from ConfigureServices because of some Design Patterns. Check that. In Startup.cs => ConfigureServices add these lines:
var connectionString = "Application Connection String!!!";
services.AddDbContext<MyDbContext>(c => c.UseSqlServer(connectionString));
In my case this error occurred due to I remove MyDbContext from ConfigureServices because of some Design Patterns. Check that. In Startup.cs => ConfigureServices add these lines:
var connectionString = "Application Connection String!!!";
services.AddDbContext<MyDbContext>(c => c.UseSqlServer(connectionString));
answered Mar 14 at 0:59
Hamed Nikzad
14414
14414
add a comment |
add a comment |
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45782446%2funable-to-create-migrations-after-upgrading-to-asp-net-core-2-0%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
Possibly the problem is not in Program.cs. It is probably the use of an instruction to load seed data at the end of your Configure method: DbInitializer.Initialize (context); If you have that instruction, comment it: //DbInitializer.Initialize(context); Then run the Migration instructions to test. If the problem arises, then follow up on the DbInitializer.cs class.
– Miguel Torres C
Aug 20 '17 at 20:17
Is your MyContext class in another class library project?
– Orhun
Aug 22 '17 at 6:37
Same issue here, context is in other library. If id add an parameter less consturctor to the context, migrations are working, but with the same error: (An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Object reference not set to an instance of an object. )
– iBoonZ
Aug 26 '17 at 11:40
Did you get it resolved in the end?
– Konrad Viltersten
Sep 8 '17 at 11:19
@MiguelTorresC thanks for that comment. I commented out my Seeding Methods and Migrations began to work again. Thanks a ton !!!
– Amit Philips
Jul 12 at 2:20