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

Cannot make migration. ef core 2.0 #9415

Closed
daviatorstorm opened this Issue Aug 15, 2017 · 44 comments

Comments

Projects
None yet
@daviatorstorm

daviatorstorm commented Aug 15, 2017

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

Using project \Backend.csproj'.
Using startup project \Backend.csproj'.
Writing '\obj\Backend.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Users\user\AppData\Local\Temp\tmpE244.tmp /verbosity:quiet /nologo \Backend.csproj
Writing '\obj\Backend.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Users\user\AppData\Local\Temp\tmpE468.tmp /verbosity:quiet /nologo \Backend.csproj
dotnet build \Backend.csproj /verbosity:quiet /nologo

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:03.33
dotnet exec --depsfile \bin\Debug\netcoreapp2.0\Backend.deps.json --additionalprobingpath C:\Users\user\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig \bin\Debug\netcoreapp2.0\Backend.runtimeconfig.json C:\Users\user\.nuget\packages\microsoft.entityframeworkcore.tools.dotnet\2.0.0\tools\netcoreapp2.0\ef.dll migrations add Test -c BackendContext --assembly \bin\Debug\netcoreapp2.0\Backend.dll --startup-assembly \bin\Debug\netcoreapp2.0\Backend.dll --project-dir \ --verbose --root-namespace Backend
Using assembly 'Backend'.
Using startup assembly 'Backend'.
Using application base \bin\Debug\netcoreapp2.0'.
Using working directory '\'.
Using root namespace 'Backend'.
Using project directory '\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding BuildWebHost method...
No BuildWebHost method was found on type 'Backend.Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'BackendContext'.
Found DbContext 'LiteContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'BackendContext'. Add an implementation of 'IDesignTimeDbContextFactory<BackendContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time. ---> System.MissingMethodException: No parameterless constructor defined for this object.
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_3.<FindContextTypes>b__13()
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_3.<FindContextTypes>b__13()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type 'BackendContext'. Add an implementation of 'IDesignTimeDbContextFactory<BackendContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

BackendContext

public class BackendContext : DbContext
{
     public BackendContext(DbContextOptions<BackendContext> options)
         : base(options)
     { }
}

In Startup.cs

services.AddDbContext<BackendContext>(opts =>
                opts.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

EF Core version: 2.0
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: win10-x64
IDE: Visual Studio 2017
.NET Core SDK info:

.NET Command Line Tools (2.0.0)

Product Information:
 Version:            2.0.0
 Commit SHA-1 hash:  cdcd1928c9

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.15063
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\2.0.0\


Microsoft .NET Core Shared Framework Host



  Version  : 2.0.0

  Build    : e8b8861ac7faf042c87a5c2f9f2d04c98b69f28d
@daviatorstorm

This comment has been minimized.

Show comment
Hide comment
@daviatorstorm

daviatorstorm commented Aug 15, 2017

Found a solution

@ajcvickers

This comment has been minimized.

Show comment
Hide comment
@ajcvickers

ajcvickers Aug 16, 2017

Member

@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.

Member

ajcvickers commented Aug 16, 2017

@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.

@Sweetog

This comment has been minimized.

Show comment
Hide comment
@Sweetog

Sweetog Sep 5, 2017

@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 commented Sep 5, 2017

@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<>

@cbmek

This comment has been minimized.

Show comment
Hide comment
@cbmek

cbmek Sep 6, 2017

@Sweetog look at paragraph dotnet ef database update and there is a comment:

In order for the EF Migrations tooling to work you MUST NAME THE METHOD: BuildWebHost just like the example ... you cannot use a different method name.

So you just need to update your Program.cs to:

    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

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

cbmek commented Sep 6, 2017

@Sweetog look at paragraph dotnet ef database update and there is a comment:

In order for the EF Migrations tooling to work you MUST NAME THE METHOD: BuildWebHost just like the example ... you cannot use a different method name.

So you just need to update your Program.cs to:

    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
@Sweetog

This comment has been minimized.

Show comment
Hide comment
@Sweetog

Sweetog Sep 6, 2017

@cbmek But the will not fix the OP's error, the OP's error specifically states: "Add an implementation of 'IDesignTimeDbContextFactory'". In the link you provided there is no text that says "you MUST NAME THE METHOD: BuildWebHost"

Sweetog commented Sep 6, 2017

@cbmek But the will not fix the OP's error, the OP's error specifically states: "Add an implementation of 'IDesignTimeDbContextFactory'". In the link you provided there is no text that says "you MUST NAME THE METHOD: BuildWebHost"

@Sweetog

This comment has been minimized.

Show comment
Hide comment
@Sweetog

Sweetog Sep 6, 2017

@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 IDesignTimeDbContextFactory:

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

Sweetog commented Sep 6, 2017

@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 IDesignTimeDbContextFactory:

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

This comment has been minimized.

Show comment
Hide comment
@cbmek

cbmek Sep 7, 2017

Changing Program.cs to one quoted in the article fixed the error for me. No IDesignTimeDbContextFactory needed.

Here is my context:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
    {
        public DbSet<SomeEntity> SomeEntities { get; set; }

        public ApplicationDbContext(DbContextOptions options) : base(options) {}
    }

Scenario 1 - old way of Program.cs

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

            host.Run();
        }
    }

...and migration (I use -s because I have all my DB stuff in separate project):
image

Scenario2 - new way of Project.cs

Just one change here:

    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

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

...and magic happen:
image

cbmek commented Sep 7, 2017

Changing Program.cs to one quoted in the article fixed the error for me. No IDesignTimeDbContextFactory needed.

Here is my context:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
    {
        public DbSet<SomeEntity> SomeEntities { get; set; }

        public ApplicationDbContext(DbContextOptions options) : base(options) {}
    }

Scenario 1 - old way of Program.cs

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

            host.Run();
        }
    }

...and migration (I use -s because I have all my DB stuff in separate project):
image

Scenario2 - new way of Project.cs

Just one change here:

    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

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

...and magic happen:
image

@Sweetog

This comment has been minimized.

Show comment
Hide comment
@Sweetog

Sweetog Sep 7, 2017

@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

Sweetog commented Sep 7, 2017

@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

@crasshacker

This comment has been minimized.

Show comment
Hide comment
@crasshacker

crasshacker Sep 13, 2017

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
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 "TakHub" requested by the login. The login failed.
Login failed for user 'SNAPPY\Computer'.)
Unable to create an object of type 'ApplicationDbContext'. 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 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 commented Sep 13, 2017

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
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 "TakHub" requested by the login. The login failed.
Login failed for user 'SNAPPY\Computer'.)
Unable to create an object of type 'ApplicationDbContext'. 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 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.

@Sweetog

This comment has been minimized.

Show comment
Hide comment
@Sweetog

Sweetog Sep 13, 2017

@crasshacker you do not need to add IDesignTimeDbContextFactory, in your Program.cs you have to have a method named "BuildWebHost":

        public static void Main(string[] args)
        {
            //you must must have a method/function name "BuildWebHost" otherwise EF Core Migrations will throw an execption that you need to have an implementation of IDesignTimeDbContextFactory
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
           WebHost.CreateDefaultBuilder(args)
               .UseStartup<Startup>()
               .Build();

Sweetog commented Sep 13, 2017

@crasshacker you do not need to add IDesignTimeDbContextFactory, in your Program.cs you have to have a method named "BuildWebHost":

        public static void Main(string[] args)
        {
            //you must must have a method/function name "BuildWebHost" otherwise EF Core Migrations will throw an execption that you need to have an implementation of IDesignTimeDbContextFactory
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
           WebHost.CreateDefaultBuilder(args)
               .UseStartup<Startup>()
               .Build();
@crasshacker

This comment has been minimized.

Show comment
Hide comment
@crasshacker

crasshacker Sep 13, 2017

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
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .Build();

}

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.

crasshacker commented Sep 13, 2017

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
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .Build();

}

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.

@crasshacker

This comment has been minimized.

Show comment
Hide comment
@crasshacker

crasshacker Sep 13, 2017

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...

crasshacker commented Sep 13, 2017

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...

@bradley-varol

This comment has been minimized.

Show comment
Hide comment
@bradley-varol

bradley-varol Sep 14, 2017

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.

bradley-varol commented Sep 14, 2017

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.

@crasshacker

This comment has been minimized.

Show comment
Hide comment
@crasshacker

crasshacker Sep 14, 2017

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.

crasshacker commented Sep 14, 2017

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.

@LevesqueJ99

This comment has been minimized.

Show comment
Hide comment
@LevesqueJ99

LevesqueJ99 Sep 24, 2017

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.

LevesqueJ99 commented Sep 24, 2017

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.

@pgmolloy

This comment has been minimized.

Show comment
Hide comment
@pgmolloy

pgmolloy Sep 26, 2017

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.
Parameter name: startIndex"
At line:1 char:1

  • Add-Migration
  •   + CategoryInfo          : NotSpecified: (:) [Add-Migration], MethodInvocationException
      + FullyQualifiedErrorId : ArgumentOutOfRangeException,Add-Migration
    
    

pgmolloy commented Sep 26, 2017

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.
Parameter name: startIndex"
At line:1 char:1

  • Add-Migration
  •   + CategoryInfo          : NotSpecified: (:) [Add-Migration], MethodInvocationException
      + FullyQualifiedErrorId : ArgumentOutOfRangeException,Add-Migration
    
    
@pgmolloy

This comment has been minimized.

Show comment
Hide comment
@pgmolloy

pgmolloy Sep 26, 2017

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
rosoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
Add-Migration : Exception calling "Substring" with "1" argument(s): "StartIndex cannot be less than zero.
Parameter name: startIndex"
At line:1 char:1

  • Add-Migration InitialCreate
  •   + CategoryInfo          : NotSpecified: (:) [Add-Migration], MethodInvocationException
      + FullyQualifiedErrorId : ArgumentOutOfRangeException,Add-Migration
    
    

PM>

pgmolloy commented Sep 26, 2017

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
rosoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
Add-Migration : Exception calling "Substring" with "1" argument(s): "StartIndex cannot be less than zero.
Parameter name: startIndex"
At line:1 char:1

  • Add-Migration InitialCreate
  •   + CategoryInfo          : NotSpecified: (:) [Add-Migration], MethodInvocationException
      + FullyQualifiedErrorId : ArgumentOutOfRangeException,Add-Migration
    
    

PM>

@pgmolloy

This comment has been minimized.

Show comment
Hide comment
@pgmolloy

pgmolloy Sep 26, 2017

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
Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
User profile is available. Using 'C:\Users\Peter Molloy\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
Microsoft.EntityFrameworkCore.Infrastructure[100403]
Entity Framework Core 2.0.0-rtm-26452 initialized 'ApplicationDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
To undo this action, use Remove-Migration.
PM>

pgmolloy commented Sep 26, 2017

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
Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
User profile is available. Using 'C:\Users\Peter Molloy\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
Microsoft.EntityFrameworkCore.Infrastructure[100403]
Entity Framework Core 2.0.0-rtm-26452 initialized 'ApplicationDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
To undo this action, use Remove-Migration.
PM>

@nzaetta

This comment has been minimized.

Show comment
Hide comment
@nzaetta

nzaetta Sep 27, 2017

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
if (context.Database.GetAppliedMigrations().Any()){
Initialise();
}

nzaetta commented Sep 27, 2017

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
if (context.Database.GetAppliedMigrations().Any()){
Initialise();
}

@asif-khan17

This comment has been minimized.

Show comment
Hide comment
@asif-khan17

asif-khan17 Sep 29, 2017

public static void Main(string[] args)
{
//you must must have a method/function name "BuildWebHost" otherwise EF Core Migrations will throw an execption that you need to have an implementation of IDesignTimeDbContextFactory
BuildWebHost(args).Run();
}

    public static IWebHost BuildWebHost(string[] args) =>
       WebHost.CreateDefaultBuilder(args)
           .UseStartup<Startup>()
           .Build();

}
I changed my program.cs as above but it is giving me an error on line WebHost.CreateDefaultBuilder(args) , that WebHost does not exist in the current context plz help

asif-khan17 commented Sep 29, 2017

public static void Main(string[] args)
{
//you must must have a method/function name "BuildWebHost" otherwise EF Core Migrations will throw an execption that you need to have an implementation of IDesignTimeDbContextFactory
BuildWebHost(args).Run();
}

    public static IWebHost BuildWebHost(string[] args) =>
       WebHost.CreateDefaultBuilder(args)
           .UseStartup<Startup>()
           .Build();

}
I changed my program.cs as above but it is giving me an error on line WebHost.CreateDefaultBuilder(args) , that WebHost does not exist in the current context plz help

@AllaouaCheraitia

This comment has been minimized.

Show comment
Hide comment
@AllaouaCheraitia

AllaouaCheraitia Oct 2, 2017

@asif-khan17 WebHost is a member of Microsoft.AspNetCore - You need to add that namespace.

AllaouaCheraitia commented Oct 2, 2017

@asif-khan17 WebHost is a member of Microsoft.AspNetCore - You need to add that namespace.

@bradley-varol

This comment has been minimized.

Show comment
Hide comment
@bradley-varol

bradley-varol Oct 10, 2017

I get this issue when using [DatabaseGenerated(DatabaseGeneratedOption.Computed)]

bradley-varol commented Oct 10, 2017

I get this issue when using [DatabaseGenerated(DatabaseGeneratedOption.Computed)]

@jitendriyag2

This comment has been minimized.

Show comment
Hide comment
@jitendriyag2

jitendriyag2 Oct 12, 2017

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

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
    {
        public AppDbContext CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
            var builder = new DbContextOptionsBuilder<AppDbContext>();
            var connectionString = configuration.GetConnectionString("MyAppCS");
            builder.UseSqlServer(connectionString);
            return new AppDbContext(builder.Options);
        }
    }

jitendriyag2 commented Oct 12, 2017

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

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
    {
        public AppDbContext CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
            var builder = new DbContextOptionsBuilder<AppDbContext>();
            var connectionString = configuration.GetConnectionString("MyAppCS");
            builder.UseSqlServer(connectionString);
            return new AppDbContext(builder.Options);
        }
    }
@liamdawson

This comment has been minimized.

Show comment
Hide comment
@liamdawson

liamdawson Oct 23, 2017

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 IDesignTimeDbContextFactory when I'm using AddDbContext on a ServiceCollection anyway...

liamdawson commented Oct 23, 2017

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 IDesignTimeDbContextFactory when I'm using AddDbContext on a ServiceCollection anyway...

@bricelam

This comment has been minimized.

Show comment
Hide comment
@bricelam
Member

bricelam commented Oct 23, 2017

@ogix

This comment has been minimized.

Show comment
Hide comment
@ogix

ogix Nov 10, 2017

For me none of the above solutions helped. But then I set my web project as startup and then it worked!

ogix commented Nov 10, 2017

For me none of the above solutions helped. But then I set my web project as startup and then it worked!

@lamhoanghiep

This comment has been minimized.

Show comment
Hide comment
@lamhoanghiep

lamhoanghiep Nov 13, 2017

@ogix "For me none of the above solutions helped. But then I set my web project as startup and then it worked!"
Cool, it works

lamhoanghiep commented Nov 13, 2017

@ogix "For me none of the above solutions helped. But then I set my web project as startup and then it worked!"
Cool, it works

@ristogod

This comment has been minimized.

Show comment
Hide comment
@ristogod

ristogod Nov 29, 2017

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
dotnet ef migrations add New_Migration

We always have to navigate to the data project first, but it always fails complaining about
Unable to create an object of type 'DbContext'. Add an implementation of 'IDesignTimeDbContextFactory<DbContext>' to the project

So then I thought what I should do is add the
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.1" />

to the web project and try running the same command there. But then it just complains
No DbContext was found in assembly 'Web'. Ensure that you're using the correct assembly and that the type is neither abstract nor generic.

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 .netcoreapp2.0 instead of what I feel should be a netstandard2.0 without a Program.cs.

ristogod commented Nov 29, 2017

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
dotnet ef migrations add New_Migration

We always have to navigate to the data project first, but it always fails complaining about
Unable to create an object of type 'DbContext'. Add an implementation of 'IDesignTimeDbContextFactory<DbContext>' to the project

So then I thought what I should do is add the
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.1" />

to the web project and try running the same command there. But then it just complains
No DbContext was found in assembly 'Web'. Ensure that you're using the correct assembly and that the type is neither abstract nor generic.

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 .netcoreapp2.0 instead of what I feel should be a netstandard2.0 without a Program.cs.

@bricelam

This comment has been minimized.

Show comment
Hide comment
@bricelam
Member

bricelam commented Nov 29, 2017

@ristogod

This comment has been minimized.

Show comment
Hide comment
@ristogod

ristogod Nov 29, 2017

Yes it does actually.

I was able to create the DesignTimeContextFactory. Then I used <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.1" /> instead of <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.1" /> which allowed me to run migrations where the project was netstandard2.0 instead of netcoreapp2.0. Thanks.

ristogod commented Nov 29, 2017

Yes it does actually.

I was able to create the DesignTimeContextFactory. Then I used <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.1" /> instead of <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.1" /> which allowed me to run migrations where the project was netstandard2.0 instead of netcoreapp2.0. Thanks.

@BikeMrown

This comment has been minimized.

Show comment
Hide comment
@BikeMrown

BikeMrown Dec 19, 2017

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()
myContext.EnsureSeedDataForContext();

BikeMrown commented Dec 19, 2017

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()
myContext.EnsureSeedDataForContext();

@jmevel

This comment has been minimized.

Show comment
Hide comment
@jmevel

jmevel Feb 16, 2018

For the record:

I had the same issue which was driving me crazy.
I finally found the root cause (in my case)

my appsettings.json had this setting:

"Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Verbose", "System": "Information", "Microsoft": "Information" } }

Simply changing it by this solved the problem:

"Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }

jmevel commented Feb 16, 2018

For the record:

I had the same issue which was driving me crazy.
I finally found the root cause (in my case)

my appsettings.json had this setting:

"Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Verbose", "System": "Information", "Microsoft": "Information" } }

Simply changing it by this solved the problem:

"Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }

@strich

This comment has been minimized.

Show comment
Hide comment
@strich

strich Feb 21, 2018

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 dotnet ef migrations add InitialCreate, it'll fail. You must run a dotnet ef database update first. Got to love those completely misleading error messages.

strich commented Feb 21, 2018

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 dotnet ef migrations add InitialCreate, it'll fail. You must run a dotnet ef database update first. Got to love those completely misleading error messages.

@smitpatel

This comment has been minimized.

Show comment
Hide comment
@smitpatel

smitpatel Feb 21, 2018

Contributor

If the db doesn't exist, and you try to dotnet ef migrations add InitialCreate, it'll fail.

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.

Contributor

smitpatel commented Feb 21, 2018

If the db doesn't exist, and you try to dotnet ef migrations add InitialCreate, it'll fail.

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.

@colotiline

This comment has been minimized.

Show comment
Hide comment
@colotiline

colotiline Mar 7, 2018

In default angular template (vs code) your BuildWebHost looks like:

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 url is gathering:

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 commented Mar 7, 2018

In default angular template (vs code) your BuildWebHost looks like:

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 url is gathering:

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();
        }
@bricelam

This comment has been minimized.

Show comment
Hide comment
@bricelam

bricelam Mar 9, 2018

Member

@colotiline It looks like this is fixed in the latest codebase.

Member

bricelam commented Mar 9, 2018

@colotiline It looks like this is fixed in the latest codebase.

@sulphy

This comment has been minimized.

Show comment
Hide comment
@sulphy

sulphy Mar 26, 2018

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.

sulphy commented Mar 26, 2018

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.

@codyclay88

This comment has been minimized.

Show comment
Hide comment
@codyclay88

codyclay88 Mar 28, 2018

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.

codyclay88 commented Mar 28, 2018

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.

@rauledo

This comment has been minimized.

Show comment
Hide comment
@rauledo

rauledo Apr 6, 2018

I found an article that helps with the problem.
Article title: How to seed your EF Core database
Link: https://garywoodfine.com/how-to-seed-your-ef-core-database/

rauledo commented Apr 6, 2018

I found an article that helps with the problem.
Article title: How to seed your EF Core database
Link: https://garywoodfine.com/how-to-seed-your-ef-core-database/

@phillhutt

This comment has been minimized.

Show comment
Hide comment
@phillhutt

phillhutt Jun 2, 2018

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".
So now I have something like this in "Startup.cs"

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services
            .AddDbContext<MyDBContext>(options => options.UseSqlite("Data Source=myDB.db"));
...

phillhutt commented Jun 2, 2018

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".
So now I have something like this in "Startup.cs"

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services
            .AddDbContext<MyDBContext>(options => options.UseSqlite("Data Source=myDB.db"));
...
@SteffenBlake

This comment has been minimized.

Show comment
Hide comment
@SteffenBlake

SteffenBlake Jul 24, 2018

Sneaky problem I encountered:

I had my FooContext defined in Foo.Business and my WebApp as Foo.Api.

However I also had a couple other projects set to startup (basically I had 4 startup projects, 1 of which was the API)

Running Add-Migration InitialCreate with Package Manager Console pointing to Foo.Business threw this strange error.

Reason being it decided to assume that Foo.Business was the startup project, despite it being a NetCore Library project.

Temporarily turning off Multiple Startup and specifically setting Foo.Api as my only startup project resolved the issue!

SteffenBlake commented Jul 24, 2018

Sneaky problem I encountered:

I had my FooContext defined in Foo.Business and my WebApp as Foo.Api.

However I also had a couple other projects set to startup (basically I had 4 startup projects, 1 of which was the API)

Running Add-Migration InitialCreate with Package Manager Console pointing to Foo.Business threw this strange error.

Reason being it decided to assume that Foo.Business was the startup project, despite it being a NetCore Library project.

Temporarily turning off Multiple Startup and specifically setting Foo.Api as my only startup project resolved the issue!

@cmjchrisjones

This comment has been minimized.

Show comment
Hide comment
@cmjchrisjones

cmjchrisjones Aug 5, 2018

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 Add-Migration and Update-Database in VS2017 via the Package Manager Console works, however if I remove the migrations, delete the database and try running dotnet ef migrations add Initial then it fails with Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

cmjchrisjones commented Aug 5, 2018

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 Add-Migration and Update-Database in VS2017 via the Package Manager Console works, however if I remove the migrations, delete the database and try running dotnet ef migrations add Initial then it fails with Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

@samlbest

This comment has been minimized.

Show comment
Hide comment
@samlbest

samlbest Aug 17, 2018

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.

samlbest commented Aug 17, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment