Lesson 6
Setting Up Data Environment
Lesson 5 covered SQL itself, the language every statement in this course eventually sends to SQL Server 2025. Before any of those statements can run, though, a Razor Pages application has to know where its database actually is. This lesson covers exactly that: making VirtualBookShelf's application "aware" of its database, the same objective this course has used since the legacy version of this page was first written.
Making an Application Aware of Its Database
Before a Web application can access a database, it must be made aware of that database's location and how to reach it. VirtualBookShelf's Web site accesses a SQL Server 2025 database. Unlike the earlier lessons in this module, there is no file sitting in the project directory the way a Microsoft Access database file would, SQL Server runs as its own service, reachable over a network connection, and the application needs a connection string that tells it exactly where that service is and how to authenticate with it.
A connection string is a single line of text containing the server's address, the specific database name, and the credentials or authentication method the application should use. Everything the application needs to locate and open a connection to VirtualBookShelf's database lives inside this one string.
This is a small piece of text with an outsized responsibility. Get it wrong, a misspelled server name, a database name that doesn't match, credentials SQL Server rejects, and nothing else in the application works, no query runs, no page that touches the database loads correctly. Getting this one setting right is what the rest of this lesson is really about.
Where Connections Used to Live: Global.asa and the Data Environment
In the Visual InterDev era this course modernizes away from, a Web application's database connections were managed through a Data Environment, an object containing one or more logical connections and command objects, controlled by a special file named Global.asa. Because Global.asa ran once when the application started and stayed active for its entire lifetime, any connection it set up became available to every page in the application without each page having to configure its own.
That model doesn't exist in ASP.NET Core. There is no Global.asa file, and there is no Visual InterDev-style Data Environment designer to click through. This isn't a renamed feature waiting to be found under a different menu, the architecture itself changed: ASP.NET Core replaced application-scoped COM objects like Global.asa with a configuration system and a dependency injection container, both built into the framework from the moment a project is created.
Where Connections Live Now: Configuration and Dependency Injection
A modern ASP.NET Core project stores its connection string in a file named
appsettings.json, under a section named
ConnectionStrings:
{
"ConnectionStrings": {
"VirtualBookShelfConnection": "Server=(localdb)\\mssqllocaldb;Database=VirtualBookShelf;Trusted_Connection=True;TrustServerCertificate=True;"
}
}
This single entry does the same job the old DSN named "VirtualBook" did in the legacy simulation: it gives a connection a short, memorable name, here
VirtualBookShelfConnection, that the rest of the application can refer to without repeating the full server address and credentials every time.
Each piece inside the connection string's value does a specific job:
Server names the SQL Server instance to connect to. (localdb)\mssqllocaldb above points at SQL Server LocalDB, a lightweight, developer-focused edition of SQL Server that installs alongside Visual Studio and runs only while needed, useful for exactly this kind of local development work. A production connection string instead names a real server address, such as VirtualBookShelf's Azure-hosted SQL Server 2025 instance from Lesson 3.
Database names the specific database on that server, VirtualBookShelf here, since a single SQL Server instance can host many separate databases at once.
Trusted_Connection=True tells the driver to authenticate using the current Windows user's own credentials rather than a separate SQL Server username and password, which works well for local development on a developer's own machine.
TrustServerCertificate=True controls whether the driver verifies SQL Server's TLS certificate against a trusted authority before trusting the encrypted connection, discussed further in the FAQ below.
Reaching this connection string from inside a Razor Page is where the real difference from Global.asa shows up. ASP.NET Core automatically builds an
IConfiguration object from
appsettings.json when the application starts, and makes that object available to any class that asks for it, through the framework's built-in dependency injection container. Nothing needs to be explicitly registered in
Program.cs the way Global.asa needed to be set up by hand; configuration access is part of the framework by default, which is a meaningfully simpler story than Visual InterDev's Data Environment ever offered.
Logical Connections and Command Objects, in ADO.NET Terms
The legacy content's two glossary terms are worth keeping, because both concepts are still real, they just have concrete names now:
- Logical connection: the association between the application and its data source. In ADO.NET terms, this is exactly what a
SqlConnection object represents, the class Lesson 4 introduced as the object that opens and holds a connection to SQL Server.
- Command object: an object used to execute queries. This is exactly what a
SqlCommand object does, also introduced in Lesson 4, wrapping a SQL statement so it can be executed against an open SqlConnection.
Where the legacy Data Environment stored a logical connection and a command object as abstract, designer-configured pieces sitting inside Global.asa, ASP.NET Core creates a
SqlConnection and a
SqlCommand directly in code, exactly when a page needs them, using the connection string retrieved from configuration.
Writing the command object directly in code, rather than configuring it once through a designer, also makes it easier to build the command safely. A
SqlCommand built with parameters, the parameterized queries the architecture diagram in Lesson 5 called out specifically, keeps user-supplied values separate from the SQL statement's own text, which is what prevents a value a customer types into a search box from being interpreted as part of the SQL statement itself.
Separating Development and Production Connection Strings
The legacy Data Environment simulation assumed a single, fixed setup: one database file, in one known folder, on one machine. A real application needs a different connection string depending on where it's running: a developer's own machine during development, and VirtualBookShelf's Azure-hosted SQL Server 2025 instance once deployed.
ASP.NET Core handles this with a second configuration file, appsettings.Development.json, which the framework automatically layers on top of appsettings.json whenever the application is running in a development environment. A connection string placed in appsettings.Development.json overrides the one in appsettings.json locally, without touching the file that gets deployed to production. This is a direct, built-in answer to a problem the legacy Data Environment never had to solve, since Visual InterDev's Data Environment designer had no concept of separate environments at all.
For VirtualBookShelf's production deployment, the connection string typically isn't stored in either JSON file. Because a production connection string usually contains real credentials, it's instead supplied through an environment variable or a secrets manager such as Azure Key Vault, read by the same IConfiguration object a Razor Page already injects, without any change to the page's own code. The page doesn't need to know where its connection string came from, only that _configuration.GetConnectionString("VirtualBookShelfConnection") returns the right one for whichever environment the application is currently running in.
Setting Up VirtualBookShelf's Data Environment: A Modern Walkthrough
The following walkthrough sets up a connection for the VirtualBookShelf project, the modern equivalent of the Global.asa simulation this page used to walk through.
- With the VirtualBookShelf project open in Visual Studio 2026, locate
appsettings.json in the Solution Explorer. This file ships with every new ASP.NET Core project and holds the application's configuration settings.
- Add a
ConnectionStrings section to the file, if one isn't already present, and add an entry named VirtualBookShelfConnection, the name this lesson will use throughout the rest of the course whenever a connection string is needed.
- Set the entry's value to the connection string for VirtualBookShelf's SQL Server 2025 database. For local development, that string names the server, usually a lightweight local instance, the specific database name, and how the application should authenticate; the example above uses Windows-integrated authentication, which is the most common choice for local development.
- Save
appsettings.json. Unlike the legacy Data Environment, there is no separate dialog to click through, no driver to select, and no DSN to register in the system registry; the connection string lives entirely in this one file, in plain text, as part of the project itself.
- In any Razor Page's code-behind class that needs to reach the database, add a constructor parameter of type
IConfiguration. ASP.NET Core's dependency injection container supplies this automatically; there is nothing further to register.
- Inside that class, call
_configuration.GetConnectionString("VirtualBookShelfConnection") to retrieve the connection string by its name, then pass it to a new SqlConnection object when the page needs to query the database.
A Razor Page's code-behind class that follows this pattern looks like this:
public class SetupDataEnvironmentModel : PageModel
{
private readonly IConfiguration _configuration;
public SetupDataEnvironmentModel(IConfiguration configuration)
{
_configuration = configuration;
}
public void OnGet()
{
string connectionString = _configuration.GetConnectionString("VirtualBookShelfConnection");
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(
"SELECT FirstName, LastName FROM Customer", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string firstName = reader.GetString(0);
string lastName = reader.GetString(1);
}
}
}
}
}
}
This single class does everything the 17-step Global.asa simulation used to accomplish across an entire wizard, name a connection, retrieve it, open it, and run a command against it, except the connection string is read from configuration rather than configured once through a designer and then hidden away inside Global.asa.
Confirming the Connection Works
The legacy simulation ended by pointing to the Project Explorer window, where the presence of vbookconn under Global.asa confirmed the connection had been set up. ASP.NET Core doesn't have an equivalent tree view to check, so confirming a connection string actually works means running the application, or a small diagnostic query, and watching what happens.
The most direct check is simply running the Razor Page above and seeing whether connection.Open() throws an exception. A connection string with a typo in the server name, or an authentication problem, fails immediately and loudly at that line, with a SqlException whose message usually names the exact problem, a server that couldn't be found, or a login that was rejected, rather than failing silently somewhere downstream. This is a meaningful improvement over the legacy wizard's own feedback, which offered a cheerful "Congratulations!" on selecting a driver but no equivalent confirmation that the connection it built would actually work once the project ran.
For an independent diagnostic check, connect to the same server and database using SQL Server Management Studio (SSMS) on Windows, or Visual Studio Code with Microsoft's SQL Server (MSSQL) extension. Use Object Explorer to inspect the Customer table and run a small query with an account that has the required permissions. Success confirms access only from that tool, with its current identity and settings; it does not guarantee that the application will connect. The application may use a different authentication method or process identity, encryption and certificate-validation settings, network access, or effective configuration. Check the connection string actually loaded by the application, including environment-specific overrides, without exposing credentials, and test the Razor Page in its intended runtime environment.
TikTok for Business
The project now has a named connection string pointing at VirtualBookShelf's SQL Server 2025 database. This same VirtualBookShelfConnection entry will be used throughout the rest of this course wherever a page needs to reach the database, through IConfiguration and ADO.NET for now, and later through Entity Framework Core once this course introduces it. You can also configure a separate connection in SSMS or Visual Studio Code with the MSSQL extension to inspect VirtualBookShelf's tables and run ad hoc queries while developing, the modern equivalent of the Query Designer the legacy version of this course once pointed to. That tool connection is separate from the application's configuration and runtime connection. In the next lesson, you will add a Razor Page to the VirtualBookShelf project and experiment with SQL statements directly.
A Few Common Questions
Why can't ASP.NET Core just use something like Global.asa? ASP.NET Core's dependency injection container already does everything Global.asa was used for, making a connection available application-wide, without needing a dedicated file or a COM-based object model. Reintroducing a Global.asa-style file would duplicate a job the framework already does, and do it less consistently than the built-in configuration system does.
What does TrustServerCertificate=True actually do, and is it safe to use here? It tells the ADO.NET driver to skip validating SQL Server's TLS certificate against a trusted certificate authority. For local development against a database running on the same machine, as in the example above, this is a common and reasonable shortcut. For VirtualBookShelf's production deployment on Azure, covered in Lesson 3's discussion of cloud hosting, this should be set to
False, with a properly issued certificate validated normally, since skipping validation on a real network connection removes a real security protection.
Does every single Razor Page need its own copy of this connection-string logic? Not usually. Most real applications wrap this pattern inside a dedicated data access class or repository, so a connection string is retrieved and a
SqlConnection opened in one place, then reused across pages. This lesson shows the pattern directly inside a page's code-behind for clarity, since this is the first time this course builds it, but repeating it verbatim on every page isn't the recommended long-term structure.
Is a connection string considered sensitive information? Yes, especially once it contains a username and password rather than Windows-integrated authentication. For a real deployment, a connection string's credentials are typically kept out of
appsettings.json entirely and supplied instead through environment variables or a secrets manager such as Azure Key Vault, with only the non-sensitive parts, or a placeholder, committed to source control.
Which database tool should I use for this course? Use SQL Server Management Studio (SSMS) on Windows, or Visual Studio Code with Microsoft's SQL Server (MSSQL) extension, to inspect tables and run queries. Azure Data Studio retired on February 28, 2026 and no longer receives updates or security fixes, so it is not recommended for this course. See
Microsoft's retirement and replacement guidance and the
MSSQL extension query quickstart. Neither separate tool is required by the application at runtime, and a successful tool connection does not replace testing the application itself.
What happens if the connection string doesn't work after cloning the project onto a different machine? This is one of the more common issues a developer runs into with connection strings, and it's almost always because
appsettings.Development.json points at a SQL Server instance, or a LocalDB name, that doesn't exist on the new machine. Since this file typically isn't committed to source control precisely because it can contain machine-specific or sensitive settings, a new developer usually needs to create their own copy locally, pointing at whatever SQL Server instance is actually available on their own machine, rather than assuming the committed
appsettings.json alone will work everywhere.
What's Ahead
This lesson replaced Global.asa and the Visual InterDev Data Environment with ASP.NET Core's configuration system and dependency injection container, connected VirtualBookShelf to its SQL Server 2025 database through a named connection string, and showed a Razor Page retrieving that connection string to open a SqlConnection and run a SqlCommand against the Customer table. This closes out Module 2's conceptual and setup work.
Module 3 begins the hands-on portion of this course: the next lesson adds a Razor Page to the VirtualBookShelf project and experiments directly with the SQL statements Lesson 5 introduced, now running against a real, connected SQL Server 2025 database rather than shown only as isolated examples.
Setting Up Data Environment
Click the Exercise link below to practice adding a connection string and configuring VirtualBookShelf's connection to its SQL Server 2025 database.
Setting Up Data Environment
