How can I get this DB entity method to work with .NET 6?

Viewed 23

I am attempting to create a web application that is capable of searching an itunes API. It will require a database so I am using Entity framework and have a context file called SearchCountContext.cs. Inside this file I have a constructor which I need to use inside of my controller to manipulate data, the problem I am having is that I do not know how to call this method since it takes in 1 parameter DbContextOptions<ItunesSearchDBEntities> options and do not know what argument I need to pass in when invoking. Can someone help me figure this out?

SearchCountContext.cs:

using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace ItunesMVC.DataAccess
{
    public partial class ItunesSearchDBEntities : DbContext
    {

        public ItunesSearchDBEntities(DbContextOptions<ItunesSearchDBEntities> options)
            : base(options)
        {
        }
        
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.UseCollation("utf8mb4_0900_ai_ci")
                .HasCharSet("utf8mb4");

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
        
        public DbSet<SearchCount> SearchCounts { get; set; }
    }
}

HomeController.cs:

using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using ItunesMVC.Models;

namespace ItunesMVC.Controllers;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public ActionResult Index()
    {
            
        ViewBag.SearchCounts = new DataAccess.ItunesSearchDBEntities().SearchCounts.OrderByDescending(a => a.Count).Take(25).ToList(); //Error here
        return View();
    }
    
    public IActionResult Privacy()
    {
        return View();
    }

    [HttpGet]
    public ActionResult Search(string Term)
    {
        try
        {
            var result = API.ItunesSearchAPI.Search(Term);
    
            ViewBag.value = Term;
            return View(result);
        }
        catch (Exception)
        {
    
            throw;
        }
    }
    
    [HttpGet]
    public ActionResult CountAndGO(string URL, string SearchTerm)
    {
        DataAccess.ItunesSearchDBEntities db = new DataAccess.ItunesSearchDBEntities();
    
        //Finding the term in database.
        var _term = db.SearchCounts.Where(a => a.Term == SearchTerm.ToLower()).FirstOrDefault();
        if (_term != null)
        {
            //If term is present Count is added
            _term.Count++;
            db.Entry(_term).State = System.Data.EntityState.Modified;
        }
        else
        {
            //Term is saved in database
            db.SearchCounts.Add(new SearchCount() { Term = SearchTerm.ToLower(), Count = 1 });
        }
        db.SaveChanges();
        if (URL == null || URL == "")
            return RedirectToAction("NoURL");
    
        return Redirect(URL);
    }
    
    public ActionResult NoURL()
    {
        return View();
    }
}
1 Answers

In your startup.cs or where you are registering your dependencies you may want to register an instance of your context (ItunesSearchDBEntities) by calling

services.AddDbContext<SimulationsDbContext>(d =>
{
    d.UseSqlServer(simulationsDbConnectionString);
});

Then you would be able to inject your ItunesSearchDBEntities context into the homecontroller, or even at the method level by using the [FromServices] attribute https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection?view=aspnetcore-6.0

Related