Unable to create a DbContext' Error when Using EF Core in .NET 8 ClassLibrary Project

Kamyab Faghih 70 Reputation points
2024-06-01T01:35:11.9766667+00:00

Hello everyone, I've developed a ClassLibrary project using .NET 8 and C#, and I've utilized EF Core 8 in it. I've defined my own models and context within it. However, when I attempt to use the add-migration command, I encounter this error:

"Unable to create a 'DbContext' of type ''. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[ZSL.Database.ApplicationDBContext]' while attempting to activate 'ZSL.Database.ApplicationDBContext'.' was thrown while attempting to create an instance. For the different patterns supported at design time, see this link."

I would appreciate it if you could guide me on this issue.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
779 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,104 questions
{count} vote

Accepted answer
  1. Hongrui Yu-MSFT 4,840 Reputation points Microsoft External Staff
    2024-06-03T05:47:56.16+00:00

    Hi,@Kamyab Faghih. Welcome to Microsoft Q&A. 

    Creating a database using DBContext in a .NET 8 ClassLibrary Project

    Example(Assume that the database is Sql Server and the development tool is Visual Studio):

    1.Create a .NET 8 ClassLibrary Project

    2.Install Microsoft.EntityFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.Design, and Microsoft.EntityFrameworkCore.Tools through Nuget

    3.Add entity class

    
        public class User
    
        {
    
            public int Id { get; set; }
    
     
    
            public string Name { get; set; }   
    
        }
    
    

    4.Add DbContext Class (Write your database connection string)

    
    public class MyDbContext:DbContext
    
    {
    
        public MyDbContext() { }
    
     
    
        public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    
        {
    
     
    
        }
    
     
    
        public DbSet<User> Users { get; set; }
    
     
    
     
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    
        {
    
            optionsBuilder.UseSqlServer("Write your database connection string");
    
        }
    
     
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
    
        {
    
            modelBuilder.Entity<User>(entity =>
            {
    
                entity.ToTable("User");
                entity.HasKey(p => p.Id).HasName("PK_User");
    
                entity.Property(p => p.Id)
    
                .HasColumnName("id")
    
                .HasColumnType("int").ValueGeneratedNever();
    
                entity.Property(p => p.Name)
    
                .HasColumnName("name");
    
            });
    
        }
    
    }
    
    

    5.Set the current project as startup project

    6.Execute the command to generate the database

    Way 1(Ensure that the current project can be built successfully):

    a.Open Developer PowerShell-> Enter the current project

    b.If dotnet ef is not installed, you need to execute this command

    dotnet tool install --global dotnet-ef
    

    c.Creating Migrations

    dotnet ef migration add init
    
    

    d.Update the database

    dotnet ef database update
    

    Way 2(Ensure that the solution can be built successfully):

    a.  Open Tools->NuGet Package Manager-> Package Manager Console

    b.  Set the Default Project as the current project

    c.  Creating Migrations

    Add-Migration Init
    

    d.  Update the database

    Update-Database
    

    You can check your program against the above examples. If you can provide a simple example that causes the error, I will be able to answer your question more accurately.

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


3 additional answers

Sort by: Most helpful
  1. Saman Raoofi 5 Reputation points
    2025-01-05T07:45:32.83+00:00

    Hi, The issue you encountered might be due to the addition of multiple startup projects in your solution. When there is only one startup project, Entity Framework Core can automatically detect and use it without any issues. However, when you have multiple startup projects, EF Core can't automatically determine which one to use for the migration, so you need to explicitly specify both the project containing the DbContext and the startup project using the full command.

    By using the full command with the -Project and -StartupProject options, you provide EF Core with the necessary information to correctly target the right projects for the migration process.

    This is a common situation when solutions grow more complex or involve multiple projects.

    Add-Migration InitialCreate -Project YourDbContextProject -StartupProject YourStartupProject

    1 person found this answer helpful.

  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.

    2 deleted comments

    Comments have been turned off. Learn more

  3. paulohenriquedasilvamota-8035 0 Reputation points
    2025-03-02T04:38:18.2033333+00:00

    I came here to put on record that none of the above solutions solve the error that was happening. In my case the solution I found was to download the Microsoft.EntityFrameworkCore.Design version to version 8.0.2 and it solved it because this problem is the incompatibility between this package and the pomelo package for MySql

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.