VALIDATE AND PERSIST DATA
DATA ENTRY WITH ADO.NET
Thanks to model binding in the title entry form what the user types in is found in the CourseCreateInputModel class in the Create method of type HTTP POST of CoursesController.
This is the code for ADO.NET Insert method.
INSERT ENTITY WITH ENTITY FRAMEWORK CORE
Again we are going to insert a course with the object model we are used to. The moment we want to add a row we use the Add(…) method of the DbContext creating a Course entity. However, the row is not added to the database immediately, but the entity is put temporarily in an internal organ the Change Tracker and is marked with Added.
It is when we call SaveChanges() that the DbContext goes to examine the contents of the Change Tracker, sees that an entity needs to be added, establishes a connection to the Database, and sends the appropriate Insert SQL commands.
When the entity has been persisted you return to the Change Tracker the Course property ID is updated, and the state changes from Added to Unchanged.
Detached tells the DbContext to forget about that entity, it is as if it never ended up there in the Change Tracker.
Now let’s look at the code to be inserted into the method.
The DbContext can persist multiple entities.
USE MODEL STATE AND DATA ANNOTATION TO VALIDATE THE INPUT
We are not yet checking that the title typed by the user is valid. Sanitization is something that comes after validation, first we check if this data is not in compliance with the rules, then we can clean it up so that the application can process it.
If the columns did not contain a valid orderby field value on which the sorting was to be done we would have gone to sanitize the user input by reassigning the properties.
Let’s look at Data Annotation.
We meet with our principal and establish some validation rules together.
Let’s look at the code with validation rules.
LINK TO CODE ON GITHUB
Download the section code15 or clone the GITHUB repository to have all sections available in your favorite editor.
Leave A Comment