| Lesson 5 | Data Types and Databases |
| Objective | Coerce scripting data types to match database types. |
int will not silently accept the text "twelve," and a column defined as decimal(10,2) will not accept a value with more precision than it was given room for.
?BookID=42 hands a script the text "42," not the number 42, and nothing forces a conversion before that text reaches an arithmetic expression, a comparison, or a database write.
int parameter simply will not compile if a string is passed to it instead. That sounds like it should make this entire lesson unnecessary, and for code that only talks to other strongly typed C# code, it largely does.
CInt function and its relatives did that job explicitly, by hand, every time, and this lesson is about where that same conversion happens in a modern Razor Pages application, because it still has to happen, just less visibly than it once did.
[BindProperty]
public int CustomerId { get; set; }
[BindProperty]
public decimal Price { get; set; }
[BindProperty]
public DateTime DateJoined { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
// CustomerId, Price, and DateJoined have already been
// converted from the submitted form strings by this point.
}
If a visitor's browser submits "abc" for CustomerId, the model binder does not throw an unhandled exception and does not silently store a zero. It adds an entry to ModelState describing the conversion failure, and checking ModelState.IsValid before doing anything else with the bound values is what catches that failure before it reaches a query. This is the direct modern descendant of calling CInt(Request.Form("CustomerID")) by hand and checking for an error: the conversion still happens on every request, but the framework performs it and reports failure in a structured, checkable way, rather than VBScript's variant holding whatever string it was given until an arithmetic operation or a database call further down the page breaks on it.
NewCustomerInput bound model from the previous lesson. Its four properties are declared as string, so no numeric or date conversion happens for that particular model, but the same binder and the same ModelState checking apply to any bound property regardless of its declared type.
[BindProperty], but plenty of values still arrive outside that mechanism, exactly where the legacy lesson's own warning about query string parameters applies most directly. A value read from Request.Query, a route value pulled from the URL path, or a value read from configuration is handed over as a raw string with no automatic conversion attached to it at all:
string rawBookId = Request.Query["bookId"];
if (!int.TryParse(rawBookId, out int bookId))
{
ModelState.AddModelError(string.Empty,
"The book identifier in the link was not valid.");
return Page();
}
// bookId is now a genuine int, safe to use in a query.
The TryParse family, int.TryParse, decimal.TryParse, DateTime.TryParse, bool.TryParse, and their relatives, is the modern, direct equivalent of VBScript's CInt, CDbl, CDate, and CBool functions. Each one attempts the same conversion VBScript's function attempted, but returns a Boolean indicating success or failure instead of raising an error when the input doesn't fit. That is a meaningfully better failure mode than the one the legacy page warns about: a malformed query string value produces a value you can check and react to, not an unhandled type mismatch partway through a page render. The Convert class, Convert.ToInt32, Convert.ToDateTime, and so on, performs the same conversions but throws an exception on failure instead of returning false, which makes it a closer behavioral match to CInt for situations where an invalid value genuinely should be treated as an exceptional condition rather than routine bad input to validate against.
SqlCommand built across this module's Update, Insert, and Delete lessons used AddWithValue to attach its parameters, and AddWithValue performs its own quiet type coercion every time it runs. It inspects the .NET type of the value handed to it and picks a matching SqlDbType on the fly: a C# string becomes NVarChar, an int becomes Int, and so on. Most of the time this inference is harmless, but it is still inference, not an explicit declaration, and it has one well-documented failure mode worth knowing about now that this lesson exists to name it directly. If a table column is defined as varchar rather than nvarchar, AddWithValue still infers NVarChar from an ordinary C# string, and SQL Server has to implicitly convert the column's values to match the parameter's type during the comparison. On a small table that costs nothing noticeable. On a large, heavily queried table, that implicit conversion can prevent SQL Server from using an index on that column at all, turning an indexed lookup into a full scan.
SqlParameter emailParam = new("@NewEmail", SqlDbType.VarChar, 100)
{
Value = newEmail
};
command.Parameters.Add(emailParam);
This is not a change this course needs to make retroactively to every earlier lesson's handler; AddWithValue remains a perfectly reasonable default for VirtualBookShelf's own columns, and none of this module's earlier examples hit the mismatch described above. It is worth knowing as the specific, concrete shape this lesson's general concern takes inside a parameterized query, because it is the same underlying question asked in every earlier lesson's command.Parameters.AddWithValue(...) line without ever being asked out loud: does the type being handed to this parameter actually match what the column expects.
ExecuteScalarAsync returns a plain object?, because ADO.NET has no way to know in advance what type a given scalar query will return:
object? result = await command.ExecuteScalarAsync();
int newCustomerId = Convert.ToInt32(result);
That second line is a type coercion in exactly the sense this lesson is about: a value arrives in a form the rest of the method cannot use directly, in this case a boxed object rather than a database-shaped string, and it has to be explicitly converted to a usable int before anything else happens with it. The mechanism is Convert.ToInt32 rather than VBScript's CInt, and the source is a database result rather than an HTTP query string, but the underlying concern, a value in the wrong shape needing an explicit conversion before use, is identical.
Integer subtype was a 16 bit value, capable of holding numbers only up to 32,767. VBScript's Long subtype was the full 32 bit value most programmers actually mean when they think of an ordinary whole number. .NET's int, which is shorthand for Int32, is a 32 bit value. Despite the name, int corresponds to VBScript's Long, not VBScript's Integer, and CLng is the closer historical ancestor of a modern int.Parse or int.TryParse call than CInt is, even though CInt looks like the obvious match by name alone. In ordinary ASP.NET Core code this distinction rarely matters, because VBScript's narrower 16 bit Integer has no direct equivalent in common use today, but it is a useful reminder not to assume a function table maps one name to one name just because the spelling looks close.
TryParse method, which returns a Boolean success flag and is the better choice when the input might be invalid, and a Convert method, which throws an exception on failure and is the closer behavioral match to VBScript's own error-raising behavior.
| VBScript | .NET equivalent | Notes |
| Asc(string) | Convert.ToInt32(str[0]) | Returns the numeric code of the first character |
| CBool(expr) | bool.TryParse / Convert.ToBoolean | Converts to Boolean |
| CByte(expr) | byte.TryParse / Convert.ToByte | Converts to an 8 bit unsigned value |
| CCur(expr) | decimal.TryParse / Convert.ToDecimal | .NET has no dedicated Currency type; decimal is the closest fit |
| CDate(expr) | DateTime.TryParse / Convert.ToDateTime | Converts to a date and time value |
| CDbl(expr) | double.TryParse / Convert.ToDouble | Converts to a double precision floating point value |
| Chr(code) | Convert.ToChar(code) / (char)code | Converts a numeric code back to a character |
| CInt(expr) | int.TryParse / Convert.ToInt32 | Common usage; VBScript's own CInt was 16 bit, see note above |
| CLng(expr) | int.TryParse / Convert.ToInt32 | The closer 32 bit historical match, see note above |
| CSng(expr) | float.TryParse / Convert.ToSingle | Converts to a single precision floating point value |
| CStr(expr) | .ToString() | Converts any value to its string representation |
| Hex(number) | number.ToString("X") | Returns an uppercase hexadecimal string |
| Oct(number) | Convert.ToString(number, 8) | Returns an octal string |
VarType function before converting it:
if VarType(oldvariable) <> 2 then
newvariable = CInt(oldvariable)
end if
VBScript's VarType function returns a numeric code identifying a variant's current subtype, and 2 is the code for the integer subtype, which is why the comparison above reads "if this variable is not already an integer." A modern Razor Pages handler rarely needs an equivalent runtime type check of its own, because C# is statically typed and a variable's declared type is already known at compile time rather than discovered at run time. The one place an analogous check does still show up is exactly where this lesson has already pointed: inspecting the boxed object? returned by ExecuteScalarAsync, or checking the Boolean result of a TryParse call, before trusting a converted value.
Why doesn't C# need a variant type the way VBScript did?
Because C# variables are declared with a specific type and checked by the compiler before the program ever runs. VBScript, by contrast, resolved every variable's actual type at run time, which is exactly why a wrong guess could slip through undetected until the script executed.
Does ASP.NET Core ever use something like a variant internally?
The closest equivalent is the object type, which can hold a reference to any value but carries no information about what that value actually is until it is cast or converted, as the ExecuteScalarAsync example above shows. It is used sparingly and deliberately, not as a general substitute for declaring real types.
What happens if model binding can't convert a submitted value?
The model binder adds an error to ModelState for that property instead of throwing an exception. Checking ModelState.IsValid before using any bound value is what catches a failed conversion before it reaches a database call.
Should every TryParse call be replaced with Convert instead?
No. Use TryParse when an invalid value is a normal, expected possibility, such as user-typed input, since it returns a Boolean rather than throwing. Use Convert when an invalid value genuinely represents a programming error or a broken assumption that should surface as an exception.
Is the AddWithValue type inference problem something this course's VirtualBookShelf examples actually hit?
No. VirtualBookShelf's own Customer and Inventory columns do not currently include the kind of varchar/nvarchar mismatch that triggers it. It's included here because it is the same coercion concern this lesson is about, surfacing in code this module already wrote.
Why did CLng end up mapping to int instead of CInt mapping to int?
Because .NET's int is a 32 bit value, which matches VBScript's 32 bit Long subtype rather than VBScript's own narrower 16 bit Integer subtype, despite the similarity in names.
Does query string data ever get automatically converted the way form data does with [BindProperty]?
Only when it's bound as a page or handler parameter using the framework's own binding attributes, such as a typed handler method parameter. A raw read from Request.Query by index or key always returns a string and needs explicit conversion.
What is the practical cost of skipping this kind of check?
The same thing the legacy page warned about: unpredictable results or outright errors, surfacing anywhere from a failed comparison to a database exception, often several steps removed from where the untyped value first entered the page.
SqlCommand rather than a classic ADO Recordset method or an Entity Framework Core DbContext. Each of those three handlers, and the retrieval code from the module before it, depended on one assumption this lesson has now made explicit: that the value handed to a SqlParameter is actually the type the column expects, and that a value read from a request is converted, deliberately, before it reaches that parameter at all. VBScript handled this with a family of C-prefixed conversion functions and a single, forgiving variant type sitting underneath all of them. ASP.NET Core handles the same underlying problem with strongly typed model binding at the boundary where most values enter a page, and with explicit TryParse and Convert calls everywhere else a string still needs to become something else before it's safe to use.