Home > Back-end >  Unable to resolve service for type Microsoft.EntityFrameworkCore.DbContextOptions .net6
Unable to resolve service for type Microsoft.EntityFrameworkCore.DbContextOptions .net6

Time:09-26

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'.'

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")));


CodePudding user response:

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();
  • Related