Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to resolve service for type Microsoft.EntityFrameworkCore.DbContextOptions .net6

i’m Using .net 6

when i will create a Controller using the VS:

Unable to resolve service type "Microsoft.Entity.FrameworkCore.DbContextOptions" 1[Biblioteca.Data.Contexto] while attempting to activate ‘Biblioteca.Data.Contexto’.’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

That is my Model:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Biblioteca.Models
{
    [Table("Livro")]
    public class Livro
    {
        [Display(Name="Id")]
        [Column ("Id")]
        [Key]
        public int Id { get; set; }

        [Display(Name = "Nome")]
        [Column("Nome")]
        [Required]
        public string Nome { get; set; }

        [Display(Name = "Arquivo")]
        [Column("Livro")]
        [Required]
        public byte[] livro { get; set; }

    }
}

That is my context:

using Biblioteca.Models;
using Microsoft.EntityFrameworkCore;

namespace Biblioteca.Data
{
    public class Contexto :DbContext
    {
        public  Contexto(DbContextOptions<Contexto> options) :base (options)
            { }

        public DbSet<Livro> Livro { get; set; }


    }
}

Program.cs:

using Biblioteca.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

builder.Services.AddDbContext<Contexto>
    (options => options.UseMySql(
        "server=localhost;initial catalog=LIVRODB;uid:root;pwd:123",
        Microsoft.EntityFrameworkCore.ServerVersion.Parse("8.0.30-mysql")));


>Solution :

I don’t think you can add additional services after doing builder.Build(); – So you probably build the service collection without the context in it.

Try switching it around. So:

builder.Services.AddDbContext<Contexto>
    (options => options.UseMySql(
        "server=localhost;initial catalog=LIVRODB;uid:root;pwd:123",
        Microsoft.EntityFrameworkCore.ServerVersion.Parse("8.0.30-mysql")));
        
var app = builder.Build();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading