Home > Software engineering >  Unable to create an object of type 'MyDBContext'. For the different patterns supported at
Unable to create an object of type 'MyDBContext'. For the different patterns supported at

Time:09-17

I am working on a project on asp.net core 6 platforms. I get an error when adding a migration. I didn't have this problem in the previous version (asp.net core 5) and MVC architecture, but I decided to use onion architecture to do this project. In asp.net core 6 there is no startup.cs file and all its settings are moved to the program.cs file, so I can't diagnose the problem properly. I also tried all the suggested solutions on the internet I even created a constructor with no parameters in the DB context file but it gave the error again

** In addition, I plan to use the Connection String in the program.cs file and not use it in the Configuration method in DBContext **

Thanks

Error after run add-migration :

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

MyDBContext :

public class AhanoDBContext : IdentityDbContext<User, Role, string, UserClaim, UserRole, IdentityUserLogin<string>, RoleClaim, IdentityUserToken<string>>
{
    public AhanoDBContext(DbContextOptions options) : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        //with this function init all mapping which available in this function(for Identity)
        builder.AddCustomIdentityMappings();
        //with this function init all mapping which available in this function(for Application->Ahano)
        builder.AddCustomAhanoMappings();
        //Take Now DateTime from Server and get value automatically
        builder.Entity<Product>().Property(b => b.PublishDateTime).HasDefaultValueSql("CONVERT(datetime,GetDate())");
    }

    public virtual DbSet<Category> Categories { set; get; }
    public virtual DbSet<Product> Products { set; get; }
    public virtual DbSet<ProductCategory> ProductCategories { get; set; }
    public virtual DbSet<ProductsImage> ProductsImages { get; set; }
    public virtual DbSet<Newsletter> Newsletters { get; set; }
    public virtual DbSet<ProductTag> ProductTags { get; set; }
    public virtual DbSet<Tag> Tags { get; set; }

}

Program.cs :

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();


// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddDbContext<AhanoDBContext>(options =>
{
//The name of the connection string is taken from appsetting.json under ConnectionStrings
options.UseSqlServer(builder.Configuration.GetConnectionString("DatabaseDBConnString"));
});


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

CodePudding user response:

Try to add

    public AhanoDBContext()
    {
    }

in your MyDBContext file. Like below, it works for me.

public class AhanoDBContext : IdentityDbContext<User, Role, string, UserClaim, UserRole, IdentityUserLogin<string>, RoleClaim, IdentityUserToken<string>>
{
    public AhanoDBContext()
    {
    }
    public AhanoDBContext(DbContextOptions options) : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        //with this function init all mapping which available in this function(for Identity)
        builder.AddCustomIdentityMappings();
        //with this function init all mapping which available in this function(for Application->Ahano)
        builder.AddCustomAhanoMappings();
        //Take Now DateTime from Server and get value automatically
        builder.Entity<Product>().Property(b => b.PublishDateTime).HasDefaultValueSql("CONVERT(datetime,GetDate())");
    }

    public virtual DbSet<Category> Categories { set; get; }
    public virtual DbSet<Product> Products { set; get; }
    public virtual DbSet<ProductCategory> ProductCategories { get; set; }
    public virtual DbSet<ProductsImage> ProductsImages { get; set; }
    public virtual DbSet<Newsletter> Newsletters { get; set; }
    public virtual DbSet<ProductTag> ProductTags { get; set; }
    public virtual DbSet<Tag> Tags { get; set; }

}

CodePudding user response:

Finally, after trying all the solutions, I could solve the problem for now, but I'm not sure if it's the right way. After adding a constructor without parameters, the AddDBContext service was not recognized in the program.cs file and I had to override the OnConfiguring method in MyDBContext and write the connection string. But I think that because I use onion architecture, this is incorrect in terms of security or other reasons, because of the program.cs file is in one layer and my context is in another layer. I will be glad if you have a solution to solve the problem of AddDBContext not being recognized and tell me if what I did will cause problems for my project in the future.

OnConfiguring method in MyDBContext :

protected override void OnConfiguring(DbContextOptionsBuilder 
 optionsBuilder)
{
  optionsBuilder.UseSqlServer("Data Source=(local);Initial 
  Catalog=AhanoDB;Integrated Security=true");
}

The method that is not recognized in file Program.cs and I keep facing the error of overriding the service :

builder.Services.AddDbContext<AhanoDBContext>(options => 
options.UseSqlServer(builder.Configuration.GetConnectionString
("DatabaseDBConnString")));

Good luck to your dear ones

  • Related