50

I face the following error when adding the migration of database in .net core

This is the error:

This is the code in Startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options => 
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
           
    services.AddDefaultIdentity<ApplicationUser>().AddEntityFrameworkStores<ApplicationDbContext>();
    services.AddControllers();
}

This is the ApplicationDbContext class:

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    { }

    public DbSet<ApplicationUser> applicationUsers { get; set; }
}

This is the ApplicationUser:

public class ApplicationUser : IdentityUser
{
    [Required]
    [Column(TypeName = "nvarchar(150)")]
    public string UserFName { get; set; }
    [Required]
    public string UserLName { get; set; }
}
H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
eman
  • 633
  • 1
  • 5
  • 12
  • 2
    Please don't post images, post code (see [editing help](https://stackoverflow.com/editing-help)). On a side-note, please check the [C# Coding Guidelines](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines) using non-standard naming conventions makes the code much harder to read for any C# developer ;) – Tseng Jan 18 '20 at 03:01
  • @Tseng I Do That :) – eman Jan 19 '20 at 10:54
  • On top of the comments below my answer, your question is rather misldeading. What version are you using? Question is tagged asp.net core 2.0 and 2.1, but your error message mentions 3.1 ??? So: a) which Version of ASP.NET Core are you using? b) which verison of the SDKs you have installed? – Tseng Jan 19 '20 at 23:33
  • i change tag of my question to version 3.0 and 3.1 of .net core – eman Jan 20 '20 at 11:05

36 Answers36

81

I found the cause of this error could be multiple things in your code. For me at least, the best way was to add verbose in command.

With that will be able to understand what is the problem. the verbose will display all steps of the execution.

In visual studio use:

add-migration Added_something -verbose

For the CLI use:

dotnet ef migrations add Added_something  --verbose
Mendy
  • 7,612
  • 5
  • 28
  • 42
AFetter
  • 3,355
  • 6
  • 38
  • 62
  • 3
    apparently this should be marked as the correct answer. – AFetter Aug 05 '20 at 01:30
  • 6
    Yeah, thanks to `verbose`, I was able to identify that I forgot to add a parameterless constructor in my `DbContext` implementation and other issues. – Nicke Manarin Nov 04 '20 at 18:52
  • 4
    Yes, this is the much better answer. My solution was totally different than others, but -verbose found it easily. "Give a man a fish and you feed him for a day; teach a man to fish, you feed him for a lifetime." – John Pankowicz Dec 18 '20 at 02:09
33

This error can also occur if multiple startup projects is selected. I set my webproject to startup project and that solved the issue for me.

Pelle Åhlander
  • 331
  • 3
  • 2
  • This was also the case for me. I think it couldn't load the settings from the appsettings.json, because that was handled by the startup.cs. – jao Apr 20 '21 at 14:54
  • 2
    you saved my bacon (or the vegan equivalent). Many thanks! – James Fleming May 24 '21 at 15:35
  • 2
    Thanks. If `AppDbContext`, the migrations and the model classes are defined in a Class Library separate from the project where `appsettings.json` and `Startup.cs` are located, you need to mark that project as the Startup Project (by right clicking on it) before executing `Update-Database`. – dpant Mar 27 '22 at 19:40
  • Thank you @Pelle the solution is spot on. – Nayanajith Jan 09 '23 at 05:43
  • Wow! Who would've thought about this :) – Gabriel Marius Popescu Jun 07 '23 at 17:09
23

My problem was solved by installing Microsoft.EntityFrameworkCore.Design nuget package.

this package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct.then install the package.

at the end Build -> Clean Solution in your project and then try running your command again.

Help Link

add migration command cli:

dotnet ef migrations add InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose 

update database command cli:

dotnet ef database update InitDatabase --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose

remove migration command cli:

dotnet ef migrations remove --project YourDataAccessLibraryName -s YourWebProjectName -c YourDbContextClassName --verbose

Entity Framework Core tools reference - .NET Core CLI

Amin Golmahalleh
  • 3,585
  • 2
  • 23
  • 36
16

I also had same problem today when I was running the dotnet ef migrations add <MigrationName>

I had three project, MainApp (Web), C# Project with DBContext and C# Project for Models.

I was able to resolve it from CLI.

dotnet ef migrations add AddCategoryTableToDb -s MainApp -p ProjectHavingDbContext
Spatz
  • 18,640
  • 7
  • 62
  • 66
Pankaj Rayal
  • 201
  • 2
  • 5
14

I had the same error when I had two constructors of my DbContext. After rearranging constructors order to parameterless constructor being first in the class fixed it. e.g.

public ProgramDbContext() : base()
{
}
public ProgramDbContext(DbContextOptions<ProgramDbContext> options) : base(options)
{
}

It must be something with dynamic DbContext object invocation with Reflection playing here.

alianto
  • 161
  • 1
  • 2
6

This error also can occur if you remove the static IHostBuilder CreateHostBuilder(string[] args) method from Program.cs for your .net core app. (This was my case)

marinoff
  • 171
  • 3
  • 6
3

Seems you are your inheritance is wrong.

public ApplicationDbContext : IdentityDbContext

should be

public ApplicationDbContext : IdentityDbContext<ApplicationUser>

or

public ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole>

if you also extend roles class.

when you want to create an context with an extended user class (instead of IdentityUser)

Tseng
  • 61,549
  • 15
  • 193
  • 205
  • 1
    i use public `ApplicationDbContext : IdentityDbContext` but the same error :( – eman Jan 19 '20 at 10:15
  • Show your Program.cs file, not sure if you are using some outdated pattern (i.e. dotnet tooling method names from 2.1 but having a 3.0 or 3.1 application – Tseng Jan 19 '20 at 20:22
  • Dont post code/extended information in comments, update your question... – Tseng Jan 19 '20 at 23:26
  • `CreateHostBuilder` is for ASP.NET Core 2.1 and newer. If you are still targeting ASP.NET Core 2.0, it won't be recognized and should be called `BuildWebhost`. See [migration docs](https://learn.microsoft.com/en-us/aspnet/core/migration/20_21?view=aspnetcore-3.1#changes-to-take-advantage-of-the-new-code-based-idioms-that-are-recommended-in-aspnet-core-21). The naming and return type of that method is important for the `dotnet` tooling to work (such as ef core command lines and migrations), since it look look in this method to know how to instantiate a DbContext for the migrations – Tseng Jan 19 '20 at 23:30
3

Try This one as of March 2021 - VS 16.9.2

I tried many of the above answers and none worked for me. My issue was that we had multiple startup projects, so that was step one. Just set a single startup project, so I set our Data project to be the startup. Still got the error. Then it hit me (thanks to the @AFetter's answer) the Data project does NOT have a connection string within it. So I set my startup project to one with an appSettings.json file that HAS a connection to the DB and then made sure the Package Manager Console's Default Project was set to the Data project and reran the command to create the migration and it worked!

Grandizer
  • 2,819
  • 4
  • 46
  • 75
3

If you come to this issue while using .Net 6 along with the new minimal hosting model, check that you're not calling builder.build() before calling the AddDbContext on builder.services.

using MyProject.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);


// Add services to the container.
builder.Services.AddRazorPages();
string relativePath = ".";
string databasePath = Path.Combine(relativePath, "MyDb.sqlite");


builder.Services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlite($"Data Source={databasePath}") //connection string
        );

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}



app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();
Donkoid
  • 376
  • 2
  • 3
  • 10
  • Excellent! such an easy miss! looked all over but I guess during the transition from startup.cs to the new minimal hosting (program.cs) people like myself are missing little things like this! thank you! fixed the issue in the new dotnet 6 way! – Dav.id May 15 '22 at 12:13
2

I found I was missing:

Microsoft.EntityFrameworkCore.Tool
Microsoft.EntityFrameworkCore.Design

I had multiple startup projects (different API's). I was at a different level in the PM console. Then I learned I had to close SQL management so I can run PM console commands.

HackSlash
  • 4,944
  • 2
  • 18
  • 44
  • Please just explain a clear step by step of how someone else would replicate your solution without apology. Sometimes a new answer can be useful to someone later on. Thanks for helping. – HackSlash Dec 24 '20 at 21:23
1

I was facing the same issue while running the dot net ef migrations script command from the azure pipeline task. I did added "-project" argument. But still was failing. Adding the "-startup-project" argument worked for me. I guess even though we specify startup class in project , for ef tool to find one we have to explicitly mention them.

Nikhil
  • 11
  • 2
1

In my case, I was missing a property in appsettings.json that was showing as Warning instead of Error

This error message is sometimes not directly related to the db context model. Check other errors in your Startup class such as missing properties/ credentials in your appsettings.json/ appsettings.Development.json

run your migration with the --verbose option to see all errors and warnings

dotnet ef migrations add YourMigrationName  --verbose
Manzur Alahi
  • 1,870
  • 23
  • 19
1

Read this article: https://learn.microsoft.com/en-gb/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#from-a-design-time-factory

The tooling tries to create a design-time DB context instance using various methods. One of those methods is to look for an implementation of the IDesignTimeDbContextFactory.

Some of the EF Core Tools commands (for example, the Migrations commands) require a derived DbContext instance to be created at design time in order to gather details about the application's entity types and how they map to a database schema. In most cases, it is desirable that the DbContext thereby created is configured in a similar way to how it would be configured at run time.

Here's how your DB context factory class might look like:

public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext> {
    public BlazorContext CreateDbContext(string[] args) {
        var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
        optionsBuilder.UseSqlite("Filename=db.sqlite3");

        return new ApplicationDbContext(optionsBuilder.Options);
    }
}
Adrian Theodorescu
  • 11,664
  • 2
  • 23
  • 30
Mark Homer
  • 960
  • 6
  • 15
1

If you are using Docker-Compose project. You need to unload the Docker-Compose project and then clean and rebuild the solution and set the startup project.

It worked for me to create the migration in EFCore.

Ahsam Aslam
  • 151
  • 9
1

I faced the same problem in .Net 6 Make sure that AddDBContext is above builder.Build

builder.Services.AddDbContext<DatabaseDBContext>(options => 
  options.UseSqlServer(builder.Configuration.GetConnectionString("sqlConnection"))
);
var app = builder.Build();

In the Program.cs file, do not write anything with builder.Services.... below

var app = builder.Build()

line otherwise it throughs an error.

Saeed Zhiany
  • 2,051
  • 9
  • 30
  • 41
0

Although OP faced the issue seemingly due incorrect usage of base classes provided by AspNet Identity, but usually we come across this error when an instance of ApplicationDbContext could not be created at design time. There are couple of solutions for this. One of them is to specify the ApplicationDbContext provider in ConfigureServices method in StartUp class:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options => {
        options.UseSqlServer(Configuration.GetConnectionString("MyConnection"));
    });
}

For other solutions, please have a look at this link: https://learn.microsoft.com/en-gb/ef/core/miscellaneous/configuring-dbcontext#onconfiguring

Dipendu Paul
  • 2,685
  • 1
  • 23
  • 20
0

I was getting the same error....except the code was working fine just minutes before. I was in the process of replacing some property attributes with Fluent API

I had three projects: WebApp, DataAccess Library and Model Library.

After trying a few unsuccessful stabs at messing with migrations...I ended up doing a Build->Clean Solution and doing a build on the WebApp. Every thing was working again...and I could not recreate the error.

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
0

This error happened to me, but at the same time I also had a An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Could not parse the JSON file.

Fixing my appsettings.json file resolved the issue.

A Petrov
  • 417
  • 1
  • 9
  • 23
0

I had the same error, just modify the program class. Net Core 3.0

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

To

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

In my case, this was due to me storing my data types and migrations in a separate "Data" project and accidentally having it set as a startup project rather than my actual startup project.

Ali Bdeir
  • 4,151
  • 10
  • 57
  • 117
0

Getting the same error...

Here's how I got there:
Created a new ASP.NET Core Web App (Model-View-Controller)
Target Framework was .NET Core 3.1 (LTS)
Authentication Type: Individual Accounts

Once the project was created...I wanted to be able to modify the register/login process.(but these pages are part of the Razor Class Library)
So to get the pages in the project: I right click the project Add->New Scaffolded Item...
And picked Identity...
Next I needed to Add-Migration InitIdentity...and this is where the errors/trouble starts.

I tried reading and working through some of the other answers with no success.
I found a solution by:
Creating the project like (above)
But this time I decided NOT to Scaffold Identity.(yet)
I put a connection string in the application.config and ran the project.
I did this before Add-Migration.
I went in to register...A screen came up and said the migration hasnt run yet and had a button to run the migration. I press it and did a refresh and all was good.
Its at this point I went back to the project and did a Add->Scafolded Item...and now there is no error and I have the Auth screens to modify.

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
0

Thoroughly inspect your appsettings file and endure it is well formed. Lookout fro missing characters or unnecessary characters

snnpro
  • 193
  • 2
0

In my case I was using a custom IdentityErrorDescriber :

  services.AddIdentity<AppIdentityUser, AppIdentityRole>()
              .AddErrorDescriber<MyIdentityErrorDescriber>() // comment this !
              .AddEntityFrameworkStores<MyDbContext>()
              .AddDefaultTokenProviders();

and in my MyIdentityErrorDescriber I was using resources to translate errors. and when I comment out the .AddErrorDescriber<MyIdentityErrorDescriber>() line the migration worked without any errors. I think the problem is either with the IdentityErrorDescriber or Resources.

nAviD
  • 2,784
  • 1
  • 33
  • 54
0

I had three projects, one with Api, second with Models and third with ApplicationDbContext. Api project was starting project. I've added Microsoft.EntityFrameworkCore.Design nuget package to Api project (it's the starting project) and problem solved.

Tomek
  • 51
  • 3
0

I faced the same error and when I added this it worked fine:

services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));
            services.AddScoped<IuserRepositorhy, UserRepository>();
Dharman
  • 30,962
  • 25
  • 85
  • 135
0

I had two Configurations for Connection Strings in the app settings file, both missing a comma to separate both. When I put the comma, the error was gone.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Joseph Wambura
  • 2,732
  • 2
  • 21
  • 24
0

This might not be your issue, but this is what caused the error on my end. If your app loads an environment variable at build time, that variable should be declared in the terminal. In my case, my app loaded my GOOGLE_APPLICATION_CREDENTIALS from a json file. I needed to export that variable before running anything related to build.

Praise
  • 188
  • 2
  • 5
0

For future reference, a simple gotcha, has got me before.

Make sure you actually have a value inside of the connection string in your appsettings.json file.

I.e.

This will throw an error:

"ConnectionStrings": {
    "ConnectionString": ""
  },

This will not:

"ConnectionStrings": {
    "ConnectionString": "Server=server;Database=db;User Id=user;Password=password!;"
  },
JC919
  • 1
  • 1
0

In my case, this error ocurred when i copied a project from tutorial repository. I managed to solve it by updating the project packages through NuGet Package Manager.

  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/32894193) – Tirolel Oct 14 '22 at 11:44
0

I found that doing the following fixed this for me within my ApplicationDbContext:

public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
        optionsBuilder.UseSqlServer("Server=(LocalDB)\\MSSQLLocalDB;Database={DbName};Trusted_Connection=True;MultipleActiveResultSets=True");
        return new ApplicationDbContext(optionsBuilder.Options);
    }
}

This does appear to be something which changes from user to user.

cai120
  • 19
  • 6
0

In my case I wanted to create the migration from my class library project.

Nuget packages installed:

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Design
  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.EntityFrameworkCore.SqlServer

    All my models and the context are located in that project.
    There is one little detail.
    When you run the migrations the builder is looking for the constructor.
    After digging through the documentation I found this: constructor without parameters
    This is how my DatabaseContext looks like:
public class RandomDataContext : DbContext
{
    public virtual DbSet<YourCustomModel> YourCustomModels { get; set; }

    public RandomDataContext()
    {

    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("your_connection_string");
    }

}

After running this in the package manager console:

dotnet ef migrations add InitialMigration --project YourProjectName

Then

dotnet ef database update --project YourProjectName

I had this problem
And when I solved it, my database was created.

Zahari Kitanov
  • 510
  • 7
  • 15
0

enter image description here

In My Case in MS Visual Studio2022 .Net 6 reinstall NuGET Packages

  1. Microsoft.EntityFrameworkCore Version 6.0.12

  2. Microsoft.EntityFrameworkCore.Design Version 6.0.12

  3. Microsoft.EntityFrameworkCore.SqlServer Version 6.0.12

  4. Microsoft.EntityFrameworkCore.Tools Version 6.0.12

Alter My DbContext ..

using Leagues.Models.Domains;
using Microsoft.EntityFrameworkCore;

namespace Leagues.Models.Context {
    public partial class FifaDbContext:DbContext {
        public FifaDbContext()
        {

        }
        public FifaDbContext(DbContextOptions options):base(options)
        {
        
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder); 
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder); 
        }
        public virtual DbSet<League> Leagues { get; set; }
        public virtual DbSet<Club> Clubs { get; set; }
        public virtual DbSet<Point> Points { get; set; }
    }
}

Confirm My AppSettings

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "FiFa": "Data Source=DESKTOP-R34I8VP;Initial Catalog=FiFaWorldCup;Integrated Security=True;"
  }
}

Confirm Program.cs

using Leagues.Models.Context;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var ConnectionStrings = builder.Configuration.GetConnectionString("FiFa");
builder.Services.AddDbContext<FifaDbContext>(option => option.UseSqlServer(ConnectionStrings));
builder.Services.AddControllersWithViews();



var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Add-Migration

enter image description here

Update-Database

enter image description here

Ragab Mohamad
  • 371
  • 2
  • 4
0

I had this same problem, this error can appear for many reasons but for my case was because of removing something in program.cs class (startup.cs in older than dotnet 6) and I removed

builder.Services.AddControllersWithViews();

accidently and when added this to my class the error fixed I hope this help you

Milad_Sh
  • 41
  • 6
  • If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/33507542) – mggSoft Dec 28 '22 at 15:43
0

After spending 2 hours, it turned out that there was one wrong character in the middle of my db password in connection string :(

Usman Farooq
  • 938
  • 8
  • 10
-1

I faced this error when I forgot to do this in Startup.cs.

services.AddTransient<IExcelMasterRepository, ExcelMasterRepository>();
Dharman
  • 30,962
  • 25
  • 85
  • 135
Gvs Akhil
  • 2,165
  • 2
  • 16
  • 33
-1

In my case, I had to delete old snapshot and migration. Steps I took were:

  1. Right-click on Migrations folder
  2. Open folder in File Explorer
  3. Select & Delete all
DavidH541
  • 59
  • 1
  • 4