_context code in Controller

Dean Everhart 1,541 Reputation points
2022-11-19T16:56:40.99+00:00
    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

Developer technologies ASP.NET ASP.NET Core
{count} votes

Accepted answer
  1. Farid Uddin Kiron MSFT 456 Reputation points Microsoft External Staff
    2022-11-28T01:12:52.377+00:00

    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,541 Reputation points
    2022-11-25T19:24:34.08+00:00

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


  2. SurferOnWww 4,706 Reputation points
    2022-11-26T00:30:47.993+00:00

    Can the following Microsoft tutorial help?

    Part 4, add a model to an ASP.NET Core MVC app
    https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-6.0&tabs=visual-studio

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

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.