.NET Core中context与_context术语含义及代码报错问题咨询
Hey there! Let's break down your questions step by step since switching from Basic, Pascal, and ASPX(VB) to C# and Razor Pages can feel like jumping into a whole new set of patterns and terminology. I’ll keep this straightforward, no jargon overload.
First: Fixing the "_context does not exist in the current context" error
From the code snippet you shared, you’ve got the right idea by declaring private readonly ContosoUniversity.Data.SchoolContext _context; at the class level and assigning it in the constructor—but here are the most common reasons you might still see this error:
- You’re using
_contextoutside the class scope: Double-check that any code referencing_contextis inside yourCreateModelclass (not in a separate method or block that’s not part of the class). - Typos or case sensitivity: C# is case-sensitive! Make sure you’re writing
_contextexactly as you declared it (lowercase underscore + "context"). - Forgot to pass the context to the parent class: If
DepartmentNamePageModelalso uses_context, your constructor needs to call the parent class constructor withbase(context)—like this:
If you skip this, the parent class’spublic CreateModel(SchoolContext context) : base(context) { _context = context; }_contextwill be null, and any code in the parent that uses it will throw an error.
Second: Why do we need model nesting/inheritance?
That CreateModel : DepartmentNamePageModel line isn’t "nesting"—it’s class inheritance, and it’s all about reusing code. Think of DepartmentNamePageModel as a shared template for pages that need to work with department data. For example:
- Maybe it has a method to load a list of departments for dropdowns
- Or it handles common permissions checks for department-related pages
- Or it has helper methods to format department names
Instead of writing that same code in every page that needs it, you put it in a base class (DepartmentNamePageModel) and have other page models inherit from it. It’s the DRY (Don’t Repeat Yourself) principle in action—saves you from copying and pasting the same logic over and over.
Third: What does the last line of the constructor do?
Let’s look at that code again:
public CreateModel(ContosoUniversity.Data.SchoolContext context) { _context = context; }
This is dependency injection, one of the core patterns in modern .NET. Here’s what’s happening:
- The .NET framework automatically creates an instance of your
SchoolContext(the class that connects to your database) for you, using the connection string and settings you configured. - It passes this instance into your
CreateModelconstructor as thecontextparameter. - The line
_context = context;saves that framework-provided instance to a private field in your class, so every method inCreateModel(likeOnPostAsyncwhen you submit a form) can use it to query or update the database.
Without this line, you’d have no way to access the database connection from your page model methods.
Quick example to tie this all together (for dropdowns!)
Let’s say your DepartmentNamePageModel has code to load department options for a dropdown. Here’s how it might look, and how your CreateModel would use it:
Base class (DepartmentNamePageModel)
public class DepartmentNamePageModel : PageModel { // We make this protected so child classes can use it too protected readonly SchoolContext _context; // This will hold the dropdown options public SelectList DepartmentOptions { get; set; } // Parent constructor requires a SchoolContext public DepartmentNamePageModel(SchoolContext context) { _context = context; } // Shared method to load departments for dropdowns protected async Task LoadDepartmentsAsync() { var departments = await _context.Departments .OrderBy(d => d.Name) .ToListAsync(); DepartmentOptions = new SelectList(departments, "DepartmentId", "Name"); } }
Child class (CreateModel)
public class CreateModel : DepartmentNamePageModel { // We call the parent constructor with the context we receive public CreateModel(SchoolContext context) : base(context) { } // The data we'll collect from the form [BindProperty] public Course NewCourse { get; set; } // When the page loads, load the dropdown options public async Task<IActionResult> OnGetAsync() { await LoadDepartmentsAsync(); // Reuse the parent's method! return Page(); } // When the form is submitted public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { await LoadDepartmentsAsync(); // Reload dropdown if validation fails return Page(); } // Use _context (from the parent class!) to save the new course _context.Courses.Add(NewCourse); await _context.SaveChangesAsync(); return RedirectToPage("./Index"); } }
In your Razor page (Create.cshtml), you can then use the dropdown like this:
<div class="form-group"> <label asp-for="NewCourse.DepartmentId"></label> <select asp-for="NewCourse.DepartmentId" asp-items="Model.DepartmentOptions"></select> </div>
This way, any other page that needs a department dropdown can just inherit from DepartmentNamePageModel and call LoadDepartmentsAsync—no need to rewrite the query every time.
内容的提问来源于stack exchange,提问作者TyneBridges

