Unable to create an object of type 'DbContext' in EF Core

Dung Do Tien Apr 19 2022 236

I am a newbie in .Net 6 and Entity Framework Core. I have created a small project and using code-first to help CRUD a table in MySql. I created a DBContext as below:

 namespace MyFirstFE.Persistence.ConnectDatabase.Context
{
  public class EcommerDbContext : DbContext
  {
    public EcommerDbContext(DbContextOptions<EcommerDbContext> options)
            : base(options)
    {
    }
    
    public virtual DbSet<NotifyHistory> Notifyhistory { get; set; }
    public virtual DbSet<User> Users { get; set; }
    public virtual DbSet<Product> Products { get; set; }
    public virtual DbSet<OrderDetail> OrderDetails { get; set; }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseMySQL("server=35.240.179.150;uid=dungdt;[email protected];database=googlenotification");
        }
    }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
       base.OnModelCreating(modelBuilder);
    }
  }
}

However when add Migration I get an error : Unable to create an object of type 'EcommerDbContext'.

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

 

It's to difficult to understand, anyone can explain to me?

I'm using VS 2022 & Window 11.

Thanks for any explaintation.

Have 1 answer(s) found.
  • C

    Ciline Slim Apr 19 2022

    I got same error with .Net 6 Entity Framework and very easy to solve by add more default contructor to your DBContext. See an example:

     public class EcommerDbContext : DbContext
      {
        public EcommerDbContext()
        {
        }
        
        public EcommerDbContext(DbContextOptions<EcommerDbContext> options)
                : base(options)
        {
        }
        
        public virtual DbSet<NotifyHistory> Notifyhistory { get; set; }
        public virtual DbSet<User> Users { get; set; }
        public virtual DbSet<Product> Products { get; set; }
        public virtual DbSet<OrderDetail> OrderDetails { get; set; }
        
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseMySQL("server=35.240.179.150;uid=dungdt;[email protected];database=googlenotification");
            }
        }
        
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
           base.OnModelCreating(modelBuilder);
        }
      }

    I hope it'll solve issue for you.

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