114

After upgrading to ASP.NET Core 2.0, I can't seem to create migrations anymore.

I'm getting

"An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: One or more errors occurred. (Cannot open database "..." requested by the login. The login failed. Login failed for user '...'"

and

"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time."

The command I previously ran was $ dotnet ef migrations add InitialCreate --startup-project "..\Web" (from the project/folder with the DBContext).

Connection string: "Server=(localdb)\\mssqllocaldb;Database=database;Trusted_Connection=True;MultipleActiveResultSets=true"

This is my Program.cs

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

    public static IWebHost BuildWebHost(string[] args) =>
       WebHost.CreateDefaultBuilder(args)
           .UseStartup<Startup>()
           .Build();
}
Itchydon
  • 2,572
  • 6
  • 19
  • 33
ruhm
  • 1,357
  • 2
  • 9
  • 10
  • 3
    Possibly the problem is not in Program.cs. It is probably the use of an instruction to load seed data at the end of your Configure method: DbInitializer.Initialize (context); If you have that instruction, comment it: //DbInitializer.Initialize(context); Then run the Migration instructions to test. If the problem arises, then follow up on the DbInitializer.cs class. – Miguel Torres C Aug 20 '17 at 20:17
  • 2
    Is your MyContext class in another class library project? – Orhun Aug 22 '17 at 06:37
  • Same issue here, context is in other library. If id add an parameter less consturctor to the context, migrations are working, but with the same error: (An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Object reference not set to an instance of an object. ) – iBoonZ Aug 26 '17 at 11:40
  • @MiguelTorresC thanks for that comment. I commented out my Seeding Methods and Migrations began to work again. Thanks a ton !!! – Amit Philips Jul 12 '18 at 02:20
  • Check in Startup.cs if there a line with `service.DbContext`. If not add and try to make a migration. – Darleison Rodrigues Jan 14 '19 at 11:49

30 Answers30

129

You can add a class that implements IDesignTimeDbContextFactory inside of your Web project.

Here is the sample code:

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

Then, navigate to your Database project and run the following from command line:

dotnet ef migrations add InitialMigration -s ../Web/

dotnet ef database update -s ../Web/

-s stands for startup project and ../Web/ is the location of my web/startup project.

resource

Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93
jaaso
  • 1,405
  • 1
  • 9
  • 10
  • 2
    I'm getting: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:\Users\XXX\Documents\Visual Studio 2017\Projects\XXX\src\XXX.Api\bin\Debug\netcoreapp2.0\appsettings.json'. My appsettings is in C:\Users\XXX\Documents\Visual Studio 2017\Projects\XXX\src\XXX.Api. – Reft Sep 01 '17 at 19:37
  • Make sure you have the appsettings.json file set to copy local should fix the issue with it not being found – Linda Lawton - DaImTo Dec 08 '17 at 11:54
  • 1
    This solution introduces a dependency on Entity Framework into your host application (in my case this is a Web project). Is there any way to get around this? I would like my Repository library to hold the EF stuff, and not introduce EF into the web app. – Banoona Dec 17 '18 at 10:29
  • Despite this is the accepted answer, this one is better: https://stackoverflow.com/a/52671330/1737395 Indeed, running the migration with --verbose flag helps greatly – barbara.post Mar 19 '19 at 09:36
82

No need for IDesignTimeDbContextFactory.

Run

add-migration initial -verbose

that will reveal the details under

An error occurred while accessing the IWebHost on class 'Program'. Continuing without the application service provider.

warning, which is the root cause of the problem.

In my case, problem was, having ApplicationRole : IdentityRole<int> and invoking services.AddIdentity<ApplicationUser, IdentityRole>() which was causing below error

System.ArgumentException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole', 
on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,
TKey,TUserClaim,TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type 'TRole'.
---> System.TypeLoadException: GenericArguments[1], 'Microsoft.AspNetCore.Identity.IdentityRole', 
on 'Microsoft.AspNetCore.Identity.UserStoreBase`8[TUser,TRole,TKey,TUserClaim,
TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type parameter 'TRole'.
tchelidze
  • 8,050
  • 1
  • 29
  • 49
  • This is weird, the command `add-migration initial` threw the error no dbcontext found but when I ran `add-migration initial -verbose` it worked perfectly. I didn't make any code changes just changed the command. Any idea why? – Train Oct 14 '18 at 02:34
  • @OrthoHomeDefense well, that's really weird. I expect `-verbose` to expose the underlying error details. Not really sure why it fixed an error. – tchelidze Oct 14 '18 at 09:28
  • 3
    Yes -Verbose helps to actually uncover the real problem. In my case haven't added AddDbContext services to startup. – sudhakarssd Dec 24 '18 at 12:54
  • Hmm for me add-migration initial worked. How come it worked while using dotnet ef migrations add initial did not? – Jon Koivula Feb 04 '19 at 17:08
  • 3
    dotnet ef migrations add InitialCreate --verbose – barbara.post Mar 19 '19 at 09:31
  • 4
    @tchelidze Thank you for that, in my case I didn't have a parameterless constructor in my ApplicationDbContext. – Tiago Ávila Apr 09 '19 at 11:15
  • 1
    This is a fantastic tip, should be the accepted answer – Avrohom Yisroel Nov 05 '19 at 15:22
  • 1
    Thank you so much, this helped me find my problem and solve it. In my case, it was a "No parameterless constructor defined for type 'Data.Access.DAL.MainDbContext'.", and therefore, I just removed the parameters from the constructor and it worked like magic! – Sarah Jan 29 '20 at 11:46
  • For reference this should be the way to solve the issue. I found out exactly what the issue was with my error. – Adam Carr Mar 18 '20 at 14:33
  • I got The term 'add-migration' is not recognized. Just adding --verbose to $ dotnet ef migrations worked for me. – David Klempfner Oct 12 '20 at 11:38
29

Solution 1: (Find the problem in 99% of cases)

Set Web Application project as Startup Project

Run the following commands with -verbose option.

Add-Migration Init -Verbose

-verbose option helps to actually uncover the real problem, It contains detailed errors.

Solution 2:

Rename BuildWebHost() to CreateWebHostBuilder(), because Entity Framework Core tools expect to find a CreateHostBuilder method that configures the host without running the app.

.NET Core 2.2

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

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

.NET Core 3.1

Rename BuildWebHost() to CreateHostBuilder()

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Solution 3:

Make sure you added Dbcontext to dependency injection: AddDbContext<TContext> will make both your DbContext type, TContext, and the corresponding DbContextOptions<TContext> available for injection from the service container. This requires adding a constructor argument to your DbContext type that accepts DbContextOptions<TContext>.

Example: In Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>(options => options.UseSqlServer(connectionString));
}

AppDbContext code:

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

}
Ali Bayat
  • 3,561
  • 2
  • 42
  • 43
  • 1
    This worked for me. Changed the BuildWebHost function in Program.cs from `public static IWebHostBuilder BuildWebHost(string[] args)` to `public static IWebHost BuildWebHost(string[] args)` with the `.Build()` now included in the function – zola25 Mar 18 '19 at 12:21
  • 2
    Guys, if you are using ASP.NET Core 2.1+ you BuildWebHost method will have a different name - CreateWebHostBuilder because of https://learn.microsoft.com/en-us/aspnet/core/migration/20_21?view=aspnetcore-2.1#changes-to-main so rename CreateWebHostBuilder to BuildWebHost and migration will find BuildWebHost and take DbContext from it. – KEMBL May 08 '19 at 12:36
  • 2
    Thanks mate, Solved after spend 2 hours to configure without using `IDesignTimeDbContextFactory` – Azri Zakaria Jun 15 '19 at 20:31
  • 3
    Thanks for "-Verbose" flag. It has helped me to find the root cause of the exception. – Sergey_T Sep 04 '19 at 20:44
23
public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

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

Just rename BuildWebHost() to CreateWebHostBuilder(), because migrations use this method by default.

Prolog
  • 2,698
  • 1
  • 18
  • 31
sherox
  • 370
  • 2
  • 11
  • I'm using a Worker as a base and ran into this with Verbose: `No static method 'CreateHostBuilder(string[])' was found on class 'Program'.`. I had moved stuff around and renamed things - it recognized the CreateHostBuilder. For what it's worth... https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio – WernerCD Jan 10 '20 at 21:09
  • 1
    @WernerCD Cuz Worker uses CreateHostBuilder() method that implements IHostBuilder of Net Core 3 – sherox Jan 12 '20 at 17:35
  • @sherox Yeah, my point being simply that this answer says "you need static CreateWebHostBuilder()" - the same applies to the console application. You need "static CreateHostBuilder()" method. This answer got me in that direction. I had "rearranged" things so that wasn't present. – WernerCD Jan 12 '20 at 17:44
12

In my case, the cause of the problem was multiple startup projects. I have three projects in my solution: Mvc, Api, and Dal. DbContext and Migrations in the Dal project.

I had configured multiple startup projects. Both Mvc and Api projects were running when I clicked Start. But in this case I was getting this error.

"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time."

I could successfully add migration after setting Mvc as the only startup project and selecting Dal in the Package Manager Console.

  • 1
    Thank you, kind of same thing happened to me. I had to change startup project to the place where Startup/Program classes exists. The error message is a bad joke. – Ľuboš Pilka May 20 '19 at 11:08
  • 1
    Output messages were really frustrating. I had no startup project selected, unexpectedly. This was the reason why dbContext could not be created. Thanks. – upkit May 31 '19 at 15:19
  • 1
    Thanks you sir ... A lot of my time is saved – Naveed Khan Sep 28 '19 at 15:47
8

In the AppContext.cs besides AppContext class add another class:

// required when local database deleted
public class ToDoContextFactory : IDesignTimeDbContextFactory<AppContext>
{
    public AppContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<AppContext>();
          builder.UseSqlServer("Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true");
        return new AppContext(builder.Options);
    }
}

This will solve your second problem:

"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project,

After that you will be able to add-migration Initial and execute it by running update-database command. However if running these commands when there is no DataBase yet in your local SqlServer you will get the warning like your first error: "An error

occurred while calling method 'BuildWebHost' on class 'Program'... The login failed. Login failed for user '...'"

But it is not error because migration will be created and it can be executed. So just ignore this error for the first time, and latter since Db will exist it won't happen again.

borisdj
  • 2,201
  • 3
  • 24
  • 31
4

Please verify that you have the reference

<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" />
Pang
  • 9,564
  • 146
  • 81
  • 122
Vladmir
  • 1,255
  • 9
  • 13
  • 5
    I'm using `` which includes that reference. I tried also including the above, but no change. – ruhm Aug 20 '17 at 16:19
4

You can try this solution from this discussion, which was inspired by this post.

public static IWebHost MigrateDatabase(this IWebHost webHost)
{
    using (var scope = webHost.Services.CreateScope())
    {
        var services = scope.ServiceProvider;

        try
        {
            var db = services.GetRequiredService<MyContext>();
            db.Database.Migrate();
        }
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred while migrating the database.");
        }
    }

    return webHost;
}
public static void Main(string[] args)
{
    BuildWebHost(args)
        .MigrateDatabase()
        .Run();
}
user2771704
  • 5,994
  • 6
  • 37
  • 38
4

Something that really helped me was this article: https://elanderson.net/2017/09/unable-to-create-an-object-of-type-applicationdbcontext-add-an-implementation-of-idesigntimedbcontextfactory/

The basic idea is that in the change over from .net core 1 to 2 all db initialization should be moved out of the StartUp.cs and into the Program.cs. Otherwise the EF tasks try and run your DB inits when doing tasks.

"There is a nice section in the official migration docs (https://learn.microsoft.com/en-us/ef/core/miscellaneous/1x-2x-upgrade) titled “Move database initialization code” which I seemed to have missed. So before you head down any rabbit holes like I did make sure this isn’t what is causing your need to add an implementation of IdesignTimeDbContextFactory."

Rtype
  • 886
  • 11
  • 32
3

From

https://learn.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation

When you create a new ASP.NET Core 2.0 application, this hook is included by default. In previous versions of EF Core and ASP.NET Core, the tools try to invoke Startup.ConfigureServices directly in order to obtain the application's service provider, but this pattern no longer works correctly in ASP.NET Core 2.0 applications. If you are upgrading an ASP.NET Core 1.x application to 2.0, you can modify your Program class to follow the new pattern.

Add Factory in .Net Core 2.x

public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
    {
        public BloggingContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
            optionsBuilder.UseSqlite("Data Source=blog.db");

            return new BloggingContext(optionsBuilder.Options);
        }
    }
Anton Swanevelder
  • 1,025
  • 1
  • 14
  • 31
3

I had this problem and this solved By Set -> Web Application(Included Program.cs) Project to -> "Set as Startup Project"

Then run -> add-migration initial -verbose

in Package Manager Console

Set as Startup Project

Ali Ahmadi
  • 563
  • 5
  • 9
  • Thank you, the only solution that worked for me was to set the web project as startup project and that is exactly what needed to be done. – user3012760 May 08 '19 at 14:27
3

If you want to avoid those IDesignTimeDbContextFactory thing: Just make sure that you don't use any Seed method in your startup. I was using a static seed method in my startup and it was causing this error for me.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
3

I was facing the error

"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time."

This is how my problem was solved. Run the below command while you are in your solution directory

 dotnet ef migrations add InitialMigration --project "Blog.Infrastructure" --startup-project "Blog.Appication"

Here Application is my startup project containing the Startup.cs class & Infrastructure is my project containing the DbContext class.

then run update using the same structure.

dotnet ef database update --project "Blog.Infrastructure" --startup-project "Blog.Application"
Manzur Alahi
  • 1,870
  • 23
  • 19
2

Previously, you configured the seed data in the Configure method in Startup.cs. It is now recommended that you use the Configure method only to set up the request pipeline. Application startup code belongs in the Main method.

The refactored Main method. Add the following references to the Program.cs:

using Microsoft.Extensions.DependencyInjection;

using MyProject.MyDbContextFolder;

public static void Main(string[] args)
{
    var host = BuildWebHost(args);

    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        try
        {
            var context = services.GetRequiredService<MyDbConext>();
            DbInitializer.Initialize(context);
        }
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred while seeding the database.");
        }
    }

    host.Run();
}
Miguel Torres C
  • 681
  • 6
  • 4
2

There's a problem with ef seeding db from Startup.Configure in 2.0 ... you can still do it with this work around. Tested and worked fine

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

Nick G.
  • 111
  • 1
  • 4
2

In my case I got the problem because I had a method named SeedData.EnsurePopulated() being called on my Startup.cs file.

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

    public void ConfigureServices(IServiceCollection services)
    {
        //
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseDeveloperExceptionPage();
        app.UseStatusCodePages();
        app.UseStaticFiles();
        app.UseSession();
        app.UseMvc(routes =>
        {
            //
        });

        SeedData.EnsurePopulated(app);
    }
}

The work of SeedData class is to add initial data to the database table. It's code is:

public static void EnsurePopulated(IApplicationBuilder app)
    {
        ApplicationDbContext context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>();
        context.Database.Migrate();
        if (!context.Products.Any())
        {
            context.Products.AddRange(
            new Product
            {
                Name = "Kayak",
                Description = "A boat for one person",
                Category = "Watersports",
                Price = 275
            },
            ....
            );
            context.SaveChanges();
        }
    }

SOLUTION

Before doing migration simply comment out the calling of SeedData class in the Startup.cs file.

// SeedData.EnsurePopulated(app);

That solved my problem and hope your problem is also solved in the same way.

yogihosting
  • 5,494
  • 8
  • 47
  • 80
1

I ran into same problem. I have two projects in the solution. which

  1. API
  2. Services and repo, which hold context models

Initially, API project was set as Startup project.

I changed the Startup project to the one which holds context classes. if you are using Visual Studio you can set a project as Startup project by:

open solution explorer >> right-click on context project >> select Set as Startup project

Vikas
  • 153
  • 2
  • 10
1

First of all make sure you have configured your database in Startup.cs In my case, i was getting this error since i didn't specify the below in Startup.cs

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection"), x => x.MigrationsAssembly("<Your Project Assembly name where DBContext class resides>")));
TheKingPinMirza
  • 7,924
  • 6
  • 51
  • 81
1

Using ASP.NET Core 3.1 and EntityFrameWorkCore 3.1.0. Overriding the OnConfiguring of the context class with a parameterless constructor only

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
           .SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile("appsettings.json")
           .Build();
        var connectionString = configuration.GetConnectionString("LibraryConnection");
        optionsBuilder.UseSqlServer(connectionString);
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Francis
  • 11
  • 2
0

I got the same issue since I was referring old- Microsoft.EntityFrameworkCore.Tools.DotNet

<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />

After upgrading to the newer version it got resolved

vinayak hegde
  • 2,117
  • 26
  • 26
0

In main project's appsettings.json file, I had set 'Copy to Output directory' to "Copy always" and it worked.

geet
  • 51
  • 2
0

Sample DB context class for .net core console applications

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System.IO;

namespace EmailServerConsole.Data
{
    public class EmailDBContext : DbContext
    {
        public EmailDBContext(DbContextOptions<EmailDBContext> options) : base(options) { }
        public DbSet<EmailQueue> EmailsQueue { get; set; }
    }

    public class ApplicationContextDbFactory : IDesignTimeDbContextFactory<EmailDBContext>
    {
        EmailDBContext IDesignTimeDbContextFactory<EmailDBContext>.CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
            var builder = new DbContextOptionsBuilder<EmailDBContext>();
            var connectionString = configuration.GetConnectionString("connection_string");
            builder.UseSqlServer(connectionString);
            return new EmailDBContext(builder.Options);
        }
    }
}
hellow
  • 12,430
  • 7
  • 56
  • 79
Isanka Thalagala
  • 1,625
  • 3
  • 16
  • 32
  • While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find [how to write a good answer](https://stackoverflow.com/help/how-to-answer) very helpful. Please edit your answer. – hellow Sep 13 '18 at 06:08
0

You also can use in the startup class constructor to add json file (where the connection string lies) to the configuration. Example:

    IConfigurationRoot _config;
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json");

        _config = builder.Build();
    }
Vio
  • 1
0

For me it was because I changed the Output Type of my startup project from Console Application to Class Library.

Reverting to Console Application did the trick.

Robouste
  • 3,020
  • 4
  • 33
  • 55
0

I had this issue in a solution that has:

  • a .NET Core 2.2 MVC project
  • a .NET Core 3.0 Blazor project
  • The DB Context in a .NET Standard 2.0 class library project

I get the "unable to create an object..." message when the Blazor project is set as the start up project, but not if the MVC project is set as the startup project.

That puzzles me, because in the Package Manager Console (which is where I'm creating the migration) I have the Default project set to a the C# class library that actually contains the DB Context, and I'm also specifying the DB context in my call to add-migration add-migration MigrationName -context ContextName, so it seems strange that Visual Studio cares what startup project is currently set.

I'm guessing the reason is that when the Blazor project is the startup project the PMC is determining the version of .NET to be Core 3.0 from the startup project and then trying to use that to run the migrations on the .NET Standard 2.0 class library and hitting a conflict of some sort.

Whatever the cause, changing the startup project to the MVC project that targets Core 2.2, rather than the Blazor project, fixed the issue

tomRedox
  • 28,092
  • 24
  • 117
  • 154
0

For me the problem was that I was running the migration commands inside the wrong project. Running the commands inside the project that contained the Startup.cs rather than the project that contained the DbContext allowed me to move past this particular problem.

mark_h
  • 5,233
  • 4
  • 36
  • 52
0

In my case setting the StartUp project in init helps. You can do this by executing

dotnet ef migrations add init -s ../StartUpProjectName
B.Kosmowski
  • 143
  • 9
0

Manzur Alahi is right! I'm trying to learn Rider by JetBrains and I had the same error when I was trying to use dotnet-ef migrations add ... in Cmd, PowerShell, etc. but when I used Visual Studio IDE I didn't have problem.

I fixed the error with:

dotnet ef migrations add InitialMigration --project "Domain.Entities" --startup-project "WebApi"

and this to update the database

dotnet ef database update --project "Domain.Entities" --startup-project "WebApi"

just like Manzur Alahi said.

Joe Mayo
  • 7,501
  • 7
  • 41
  • 60
Elias Bobadilla
  • 131
  • 1
  • 2
0

If context class is in another class library project and this error is occurred, change command line default project to the context project and set solution startup project to the main API / ASP.net core project (that your DI container is there), then re-run command It seems ef core tools package has this bug a reported in https://github.com/dotnet/efcore/issues/23957 and https://github.com/dotnet/efcore/issues/23853

ARTAV
  • 82
  • 1
  • 7
-3

I had same problem. Just changed the ap.jason to application.jason and it fixed the issue

AliAzra
  • 889
  • 1
  • 9
  • 28