Efcore: Cannot make migration. ef core 2.0

Created on 15 Aug 2017  路  48Comments  路  Source: dotnet/efcore

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
closed-question

Most helpful comment

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

All 48 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 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 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"

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

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

}
```

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

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.

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

  • Add-Migration
  • ~~~~~

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

    • FullyQualifiedErrorId : ArgumentOutOfRangeException,Add-Migration

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>

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>

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

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 WebHost is a member of Microsoft.AspNetCore - You need to add that namespace.

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

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

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 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!"
Cool, it works

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 Does this docs page help?

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.

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

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" } }

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.

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.

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 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.
Article title: How to seed your EF Core database
Link: https://garywoodfine.com/how-to-seed-your-ef-core-database/

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"));
...

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!

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.

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.

     public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

  public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();

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

Thank you so much, just change the name of CreateWebHostBuilder solved the problem

Thank you so much, just change the name of CreateWebHostBuilder solved the problem

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?

Was this page helpful?
0 / 5 - 0 ratings