_context code in Controller

Dean Everhart 1,536 Reputation points
    namespace MovieDB.Controllers  
        public class MovieController : Controller  
            private readonly MovieContext _context;                                   <- Where did _context come from?  Why not reference actual name of context?  
            public async Task<IActionResult> Index(string searchString)  
                var movies = from m in _context.Movie                                  <- _context referenced here along with Movie Property Set contained / defined within the context.  
                             select m;  
                if (!String.IsNullOrEmpty(searchString))  
                    movies = movies.Where(s => s.Title!.Contains(searchString));  
               return View(await movies.ToListAsync());  

Referenced from: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-6.0

A set of technologies in the .NET Framework for building web applications and XML web services.
4,390 questions
{count} votes

Accepted answer
  1. Farid Uddin Kiron MSFT 456 Reputation points Microsoft Vendor

    Hi @Dean Everhart , Your _context will come from the service you have initialized earlier on your program.cs file as like this builder.Services.AddDbContext<MvcMovieContext>. However, you have to initialize your constructor as well as like this. Would you kindly let me know if you have any further concern.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Dean Everhart 1,536 Reputation points

    I'd like to accept answers above but it is not giving me the option to.

  2. SurferOnWww 2,486 Reputation points

    Can the following Microsoft tutorial help?

    Part 4, add a model to an ASP.NET Core MVC app

    To answer to your question see the sections "Dependency injection" and "Dependency injection in the controller".

    0 comments No comments