Adding Methods to the StudentDataAccess Class for ASP.NET 2.0
(Page 1 of 5 )
Today we continue developing the StudentDataAccess class we discussed in the previous two articles. In particular, we will create the InsertNewStudent(), UpdateStudent(), DeleteStudent() and finally the SaveStudent() methods. Keep reading to learn more in this conclusion to a three-part series.
Both the InsertNewStudent() and the UpdateStudent() will be defined as private whereas the DeleteStudent() and the SaveStudent() methods will be defined as public. When the client application, the web page in our case, calls the SaveStudent() method it will determine whether it needs to insert a new student record in the database or update the existing one based on the studentId field's value of the StudentDataAccess class. As we have seen in the previous article, we have used the studentId field's value to make a few decisions, and we continue using it today.
For example, in the parameterized constructor of the StudentDataAccess class, the one that accepts the studentId value, we built our code to test whether the user has supplied a valid studentId value; if we didn't find a matching record in the database we set the studentId field's value to -1, which means that we couldn't initialize the object from the database.
Today, we use the studentId field to determine if the user is inserting a new record or updating an existing one. Add the following SaveStudent() method definition to the StudentDataAccess class:
public void SaveStudent()
{
if (this.studentId == -1)
this.InsertNewStudent();
else
this.UpdateStudent();
}
Note that the SaveStudent() method is defined as public, and it's not a static method, because it works on instances of the StudentDataAccess class, which makes sense. In this method we use the studentId field's value to determine what we want to do. If the value is equal to -1, which means that the current StudentDataAccess instance has not been initialized from the database, then we call the instance private method InsertNewStudent() to insert a new record in the Students table.
If the value of the studentId field is not equal to -1 then we know that we have initialized the StudentDataAccess instance from the database. This is correct only if the user has assigned values to the properties of the current StudentDataAccess object, and the caller called the SaveStudent() method to submit changes made to the current StudentDataAccess instance to the database, and we need to call the UpdateStudent() method.
Let's discuss both the InsertNewStudent() and UpdateStudent() methods that are conditionally called from the SaveStudent() method.
Next: The InsertNewStudent() and UpdateStudent() methods >>
More ASP.NET Articles
More By Michael Youssef