-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Cannot make migration. ef core 2.0 #9415
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Found a solution |
@daviatorstorm Updating an ASP.NET Core application from 1.1 to 2.0 is covered by this doc: https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/ It would be great if you could comment on the doc with any issues you ran into that are not covered by the guide. |
@ajcvickers Hi, thanks the your the link you shared (https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/). But this article does not give a single example of implementing IDesignTimeDbContectFactory<> |
@Sweetog look at paragraph
So you just need to update your Program.cs to:
|
@cbmek In addition, here is a recommendation to rename Program.BuildWebHost to fix another issue. I just ran EF Core 2.0 migrations against the Program.cs below and had no issues. I just really do think what you say is the problem is what the problem is for the OP, the problem that the OP has no implemented using System.IO;
using System.Reflection;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Tsl.Example
{
public class Program
{
public static void Main(string[] args)
{
FooBuildWebHost(args).Run();
}
/// <summary>
/// This the magical WebHost.CreateDefaultBuilder method "unboxed"
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
public static IWebHost FooBuildWebHost(string[] args)
{
return new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
if (env.IsDevelopment())
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
}
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
})
//.UseIISIntegration()
.UseDefaultServiceProvider((context, options) =>
{
options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
})
.UseStartup<Startup>()
.Build();
}
}
} |
@cbmek you are correct! wow and here I wasted so much time implementing IDesignTimeDbContextFactory and I was so bothered that I had to load appsettings again and none of the articles online even gave a thought about environment specific appsettings and all I need was a method named BuildWebHost |
I'm having the same problem, and it's got me completely confused. My code had been working, but I suspected problems with my database so I decided to delete it and start fresh. Whereas previously I had been able to create the database (by adding a migration and updating), this process now fails. My Program.cs file has the standard "public static IWebHost BuildWebHost(string[] args)" method, but "Add-Migration InitialCreate" now displays a large stack trace indicating repeated failures to login to the database (which makes sense as it doesn't yet exist), and eventually prints this: Error Number:4060,State:1,Class:11 I tried creating a IDesignTimeDbContextFactory subclass with a CreateDbContext method, which also failed (but strangely told me I could use Remove-Migration to remove the migration, even though the migration failed). Has anyone got any ideas on what might be causing this issue? It's got me completely stuck at this point. |
@crasshacker you do not need to add IDesignTimeDbContextFactory, in your Program.cs you have to have a method named "BuildWebHost":
|
Yes, as I stated in my note, "My Program.cs file has the standard "public static IWebHost BuildWebHost(string[] args)" method." It looks exactly like your example. Here's my complete Program class: public class Program
} I only tried creating a class inheriting from IDesignTimeDbContextFactory after I originally got the error message, but doing so didn't help. So neither the BuildWebHost method nor the IDesignTimeDbContextFactory class are working. Which is driving me crazy, as at one point in the path this was working fine, and I haven't made any changes to my database model or much of anything else. |
I think I'm going to just create a new project from scratch, with the same database model classes, and see if I can use that to get a database built. Somehow I don't think I'll have much success, but I guess it's worth a try - especially as I have no other ideas on how to proceed. Sigh... |
I just deleted a db table, went to migrate and now i'm having this issue too. My Program.cs is exactly as recommended in the 1.x - 2.x docs. |
I'm an idiot! It turned out that I had been indirectly calling code from my ConfigureServices method that expected the database to already exist, and that code threw an exception when it didn't. It sure would have been nice if that exception had propagated up and was displayed in the output of "Add-Migration" or "dotnet ef migrations add", but alas it did not propagate and was not displayed. Still, my fault. Sigh. |
If someone also has this problem be sure that the solution you are doing add-migration is your project solution and not your test solution... It gave me this error when I was trying to do this command on my test solution, but not on my project solution. |
I have this problem using the template MVC authentication project directly from visual studio 17. The Add-Migration gives this error when trying create a new migration. Add-Migration : Exception calling "Substring" with "1" argument(s): "StartIndex cannot be less than zero.
|
I just went and followed the tutorial, interesting second line in the paste below, it reads rosoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0] anyone know what is going on. NOT GOOD, BAD PASTE FROM PM PM> Add-Migration InitialCreate
PM> |
OK just tried a whole reboot of all and loaded a new 1.1 project and migrations worked normal. Then added a 2.0 project and did migration and here's the result (notice the second line). Not sure why there is a difference after only loading a 1.1 project prior. PM> Add-Migration init |
Silimiar to @crasshacker, calling a db initialise/seed from within startup.configure which worked fine in core 1.1 but in 2.0 is causing this same 'Add an implementation of 'IDesignTimeDbContextFactory'' error Wrapped the call to test applied for any migrations |
public static void Main(string[] args)
} |
@asif-khan17 WebHost is a member of Microsoft.AspNetCore - You need to add that namespace. |
I get this issue when using |
We can create a new class file into our solution and add the following code into it then use add-migration it will definitely work
|
Can we get a convention that behaves similarly, but doesn't require anything ASP.Net Core specific? I'm writing CLI tools here with no web interface, I don't want to have to implement an |
@liamdawson You may be looking for aspnet/DependencyInjection#524 |
For me none of the above solutions helped. But then I set my web project as startup and then it worked! |
@ogix "For me none of the above solutions helped. But then I set my web project as startup and then it worked!" |
This is the part that is confusing me profusely. All the code example are always provided out of context, so I'm never quite sure where to apply these fixes. Our solution doesn't have the DbContext in the same assembly as Web Project. We have a Data project that has DbContext defined in it. So it doesn't contain startup.cs because it's not the project that runs. So when we run migration using a command like this We always have to navigate to the data project first, but it always fails complaining about So then I thought what I should do is add the to the web project and try running the same command there. But then it just complains So am I forced to have multiple Program.cs/Startup.cs, one for the Web project, and another for the Data project? It seems odd that I should have to because it forces me to make my Data project a |
@ristogod Does this docs page help? |
Yes it does actually. I was able to create the DesignTimeContextFactory. Then I used |
I had scrapped a database, deleted my migrations and tried to start over and started getting this error message. All I did to get Add-Migration to work again was comment out the seeding method call in Configure() |
For the record: I had the same issue which was driving me crazy. my appsettings.json had this setting:
Simply changing it by this solved the problem:
|
Seems this particular issue has a couple of a root causes and we STILL aren't there yet in working it all out. I will provide another GOTCHA: If the db doesn't exist, and you try to |
It does not. How are you supposed to create very first migration which creates database. Adding migration is working correctly for me when database does not exist. If you are facing issues with it then file a new issue with a solution which repros the issue. |
In default angular template (vs code) your public static IWebHost BuildWebHost(string[] args, string url) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls(url)
.Build(); EF migrations can't work with the second parameter, so just remove it and change the place where public static IWebHost BuildWebHost(string[] args) {
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("hosting.json");
var configuration = builder.Build();
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls(configuration["url"])
.Build();
} |
@colotiline It looks like this is fixed in the latest codebase. |
In case this helps anyone. I had the exact same error while creating a new project with an n-Tier design. At some point I had set my data access layer as the default startup project. I found that migrations worked again once I set the startup project to the web project where startup.cs and project.cs resides. |
I had this problem as well, I removed some seeding logic that I had used for the initial creation and it everything worked after that. |
I found an article that helps with the problem. |
In case this helps anyone. I was getting the "Add an implementation of 'IDesignTimeDbContextFactory'" error too. For me it was because I was not adding the DBContext to my service provider. In my case I happened to be changing from using a SQL Server database to a SQLite one. I had accidentally removed the "UseSqlServer" line without adding back a "UseSqlite".
|
Sneaky problem I encountered: I had my However I also had a couple other projects set to startup (basically I had 4 startup projects, 1 of which was the API) Running Reason being it decided to assume that Temporarily turning off Multiple Startup and specifically setting |
Similar but not quite the same as @SteffenBlake, I have a single project solution (technically 2 projects as the second project is Docket/dcproj), but with the non-docker project set as the startup project, and running |
This message may surface if you have an error anywhere in your startup process even if everything else is configured correctly. For me, in Startup.cs I was trying to parse a key which didn't exist in appsettings.json. I forgot that I had renamed it and never tried running the application which probably would have shown me the exception. |
I also faced this problem but then I tried to create a sample project in core 2.1, where I got the default implementation and it solved my problem for the existing project also.
|
That solved this problem for me, too. But why is that? The documents say you should rename it from BuildWebHost to CreateWebHostBuilder. It worked well for a long time and suddenly it didn't work anymore. Is there an explanation? |
@neptrio Something sounds wrong here. Could you submit a new issue with the code that was working but stopped? |
I've migrated from .NET Core 1.1 to .NET Core 2.0. Have some troubles with EF Core 2.0. I'm using multi environment.
dotnet-ef
command missing-e
(environment) option, that is required in my project.dotnet ef migrations add Test -c BackendContext -v
Error
BackendContext
In Startup.cs
EF Core version: 2.0
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: win10-x64
IDE: Visual Studio 2017
.NET Core SDK info:
The text was updated successfully, but these errors were encountered: