eman
eman

Reputation: 713

Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time

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

Upvotes: 58

Views: 118067

Answers (30)

EZEJI UDOKA AKANS
EZEJI UDOKA AKANS

Reputation: 1

You are trying to run an incorrect dependency injection.

Instead of this...

services.AddDbContext<ApplicationDbContext>(options => 
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

modify to this...

services.AddDbContext<ApplicationDbContext>(options => 
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

or this...

var connection = builder.Configuration.getConnectionstring("DefaultConnection");

builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connection));

Upvotes: -1

Usman Farooq
Usman Farooq

Reputation: 1098

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

Upvotes: 0

DavidH541
DavidH541

Reputation: 77

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

Upvotes: -2

Milad_Sh
Milad_Sh

Reputation: 51

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

Upvotes: 0

Ragab Mohamad
Ragab Mohamad

Reputation: 708

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

Upvotes: 0

Zahari Kitanov
Zahari Kitanov

Reputation: 578

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.

Upvotes: 0

cai120
cai120

Reputation: 29

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.

Upvotes: 0

luiscarlos
luiscarlos

Reputation: 1

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.

Upvotes: 0

JC919
JC919

Reputation: 1

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!;"
  },

Upvotes: 0

M. Muhammadsodiq
M. Muhammadsodiq

Reputation: 155

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.

Upvotes: 2

Mark Homer
Mark Homer

Reputation: 1035

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

Upvotes: 1

Praise
Praise

Reputation: 328

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.

Upvotes: 0

Joseph Wambura
Joseph Wambura

Reputation: 3396

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.

Upvotes: 0

Ryan
Ryan

Reputation: 455

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

Upvotes: 5

Ahsam Aslam
Ahsam Aslam

Reputation: 159

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.

Upvotes: 1

user14898166
user14898166

Reputation: 26

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

Upvotes: 0

Gvs Akhil
Gvs Akhil

Reputation: 2644

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

services.AddTransient<IExcelMasterRepository, ExcelMasterRepository>();

Upvotes: -1

Tomek
Tomek

Reputation: 71

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.

Upvotes: 0

Amin Golmahalleh
Amin Golmahalleh

Reputation: 4206

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

Upvotes: 27

nAviD
nAviD

Reputation: 3281

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.

Upvotes: 0

snnpro
snnpro

Reputation: 307

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

Upvotes: 0

Chris Catignani
Chris Catignani

Reputation: 5306

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.

Upvotes: 0

Manzur Alahi
Manzur Alahi

Reputation: 2096

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

Upvotes: 1

Grandizer
Grandizer

Reputation: 3025

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!

Upvotes: 5

Ali Bdeir
Ali Bdeir

Reputation: 4375

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.

Upvotes: 0

Nicol&#225;s Snider
Nicol&#225;s Snider

Reputation: 21

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.

Upvotes: 2

alianto
alianto

Reputation: 181

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.

Upvotes: 16

Pankaj Rayal
Pankaj Rayal

Reputation: 231

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

Upvotes: 19

Nikhil
Nikhil

Reputation: 21

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.

Upvotes: 1

Josue Pe&#241;a
Josue Pe&#241;a

Reputation: 1

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

Upvotes: 0

Related Questions