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

Cannot implicitly convert type probably in controller

I am receiving the following error: Cannot implicitly convert type: 'Microsoft.EntityFrameworkCore.DbContextOptions<TvApi.Data.TvMazeContext>' to 'TvApi.Data.TvMazeContext' TvApi

Something is wrong in this part db = context of my controller but I don’t know what:

public ShowsController(ILogger<ShowsController> logger, DbContextOptions<TvMazeContext> context)
        {
            _logger = logger;
            db = context;
        }

This is my controller:

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

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TvApi.Data;
using TvApi.Models;

namespace TvApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ShowsController : Controller
    {
        private readonly ILogger<ShowsController> _logger;
        private readonly TvMazeContext db;

        public ShowsController(ILogger<ShowsController> logger, DbContextOptions<TvMazeContext> context)
        {
            _logger = logger;
            db = context;
        }


        [HttpGet]
        public async Task<IActionResult> Index()
        {
            return View(await db.shows.ToListAsync());
        }

    }
}

My DbContext

using Microsoft.EntityFrameworkCore;
using TvApi.Models;

namespace TvApi.Data
{
    public class TvMazeContext : DbContext
    {
        public TvMazeContext(DbContextOptions<TvMazeContext> options) : base(options)
        {

        }

        public DbSet<Show> shows { get; set; }
        public DbSet<Cast> casts { get; set; }
        public DbSet<ShowCast> showCasts { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Show>().ToTable("Show");
            modelBuilder.Entity<Cast>().ToTable("Cast");
            modelBuilder.Entity<ShowCast>().ToTable("ShowCast");
        }

    }
}

My program.cs

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using TvApi.Data;

var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration;

//Database
builder.Services.AddDbContext<TvMazeContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    try
    {
        TvMazeContext dbcontext = (TvMazeContext)scope.ServiceProvider.GetService(typeof(TvMazeContext));
        await DbInitializer.InitializeAsync(dbcontext);
    }
    catch (Exception ex)
    {
        var Logger = services.GetRequiredService<ILogger<TvMazeContext>>();
        Logger.LogError(ex, "An error occured creating the DB");
    }

}

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

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

What am I doing wrong, that causes the error?

>Solution :

Instead of using DbContextOptions<TvMazeContext> in the constructor, use TvMazeContext as the injected service in which you have registered the TvMazeContext in the Program.cs.

public ShowsController(ILogger<ShowsController> logger, TvMazeContext context)
{
    _logger = logger;
    db = context;
}
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