Home > Back-end >  MySql.EntityFramework a suitable constructor could not be located
MySql.EntityFramework a suitable constructor could not be located

Time:12-07

It's the first time i'm trying to use an EntityFramework for doing operations on DB.

My DB is set in MySQL so i've installed all needed NuGets packages for it and i was trying to set the MySql.EntityFrameworkCore but when i try to run the program i get the following error:

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: VisualPos.Data.MyDbContext Lifetime: Scoped ImplementationType: VisualPos.Data.MyDbContext': A suitable constructor for type 'VisualPos.Data.MyDbContext' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.)'

My code looks like this:

Program.cs

using Microsoft.EntityFrameworkCore;
using VisualPos.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddDbContext<MyDbContext>(options => options.UseMySQL(builder.Configuration.GetConnectionString("Default")));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build(); // CODE CRASH HERE

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

MyDbContext.cs

using Microsoft.EntityFrameworkCore; using VisualPos.Models;

namespace VisualPos.Data
{
    public class MyDbContext : DbContext
    {
        protected MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
        {
        }
        
        public DbSet<Cfg> Cfg { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

        }
    }
}

Then in my controller i would just do _context.Cfg.ToList(); where _context is MyDbContext context.

The cfg table yet exists in DB.

CodePudding user response:

The solution is in the error message:

A suitable constructor for type 'VisualPos.Data.MyDbContext' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.

Your constructor is protected. It should be:

public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
  • Related