简体   繁体   中英

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

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM