Asp.net core error: Unable to create an object of type 'ApplicationDBContext'.

Dung Do Tien May 30 2021 389

When working with FE core, I have created a ApplicationDBContext inherited from DbContext:

using System;
using Domain;
using Microsoft.EntityFrameworkCore;

namespace Persistence
{
    public class ApplicationDBContext: DbContext
    {
        public ApplicationDBContext(DbContextOptions options) : base(options){}

        public DbSet<Student> Students { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(
                @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=test123;Integrated Security=True");
        }
    }
}

when I running command to help migrations database

dotnet ef migrations add initcreate -s ..\API\

But I got an error:

Unable to create an object of type 'ApplicationDBContext'. For the different patterns supported at design time, 
see https://go.microsoft.com/fwlink/?linkid=851728

Please tell me how can I resolve it?

Have 3 answer(s) found.
  • d

    dang thanh tuan May 30 2021

    When you move your DbContext to another project you should do this:

    if you use visual studio:

    right-click on your main project and choose "Set as startup project"
    then run tools > NuGet package manager > package manager console
    make sure you have chosen the project which contains your DbContext (from drop-down list)
    and run: Add-Migration .....

    if you use dotnet-cli just type this in terminal:

    dotnet ef migrations add MigrationName -s mainProject -p DbContextProject

    make sure in the terminal you are in the directory which contains both main and DbContext project

  • M

    Mahery Andriniaina Razafimanantsoa May 30 2021

    You get that error because to generate migrations you need either:

    Solution 1: A DbContext with a default constructor (that is, a parameterless constructor)

    Solution 2: Being able to get the DbContext from ApplicationServices (that is, Dependency Injection)

    Solution 3: A design-time factory that returns a properly configured DbContext.

    Hope this helps you!

  • D

    Dorian G. Ramos May 30 2021

    Solution for someone who has multiple projects:

    I had the same issue and solved it by selecting one project as a startup project instead of multiple projects.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close