Reputation: 57
Can someone explain the meaning of these two terms to me: "_context" and "context"?
Coming from Basic, Pascal, and ASPX (VB) to C# and Razor pages, I constantly misunderstand the recent .NET terminology. I believe that the only essential context (that's referred to as such) in my database application is the context - that is, a class deriving from DbContext that handles database connections. However, this always seems to be handled in an oblique way. I see examples in tutorials like this:
public class CreateModel : DepartmentNamePageModel
{
private readonly ContosoUniversity.Data.SchoolContext _context;
public CreateModel(ContosoUniversity.Data.SchoolContext context)
{
_context = context;
}
If the first line within the function is creating a new instance of the context, why (since I already have this defined and able to list items from my tables) do I get a syntax error
The name '_context' does not exist in the current context"
when I adapt it into my own code? I've added all the references from the top of the example pages. Why do we need a model within a model here, and what does the last statement do?
I've looked in this tutorial for clarification and done searches, but everything I read seems to assume we're already fluent in this way of using objects. I particularly need to grasp this because the only working example of a dropdown I can find uses these cross-references, and what I expected to be a simple task has tied me in knots.
Upvotes: 2
Views: 2748
Reputation: 13767
The constructor gets an instance of ContosoUniversity.Data.SchoolContext
(injected, for example) and then you set it to a field called _context
. Both variables are referencing the same object. If you didn't want to have two different names, you would use "this" like this:
public class CreateModel : DepartmentNamePageModel
{
private readonly ContosoUniversity.Data.SchoolContext context;
public CreateModel(ContosoUniversity.Data.SchoolContext context)
{
this.context = context; // "this" refers to the field defined in this class and not the parameter of the constructor
}
Upvotes: 4