ASP.NET Web Forms

Code First - Data Access Layer

Adding Entities as Classes

For each Entity in the proposed database there needs to be a corresponding C# class. Whilst entities or tables have plural names, classes are singular.

To customise each attribute and ensure data validation, annotations are added using the System.ComponentModel.DataAnnotations library. To link these classes to a database requires a DbContext class with a DbSet<> for each of the main entities or database tables. Some relational tables need not be mapped in this way, but rather by establishing a relationship between two entities (see example below)

In the above example the Qualification class is part of a single Specification, so the SpecificationID and the Specification itself are included (M:1 relationship). A Qualification does however contain many different Units, so a Collection of Units is part of the Qualification (1:M Relationship). A Many-to-Many relationship can also be established, and a relational table is automatically created.

Create DbContext Class

A Database Context class is added to the Models folder, the base parameter DerekWines is the name of the database connection string which is added later define the SQL Server database which is created from the classes.

Seeding the Database

Once the initial database has been created, it is usual that many changes and extensions will be added until the final application is all built. It is difficult and time consusming to arrange for data to migrate from an old version of the database to a newer version. It is easier to modify code that seeds the database with sample data each time a change is made to the database.

The class above uses a base class that deletes and re-creates the database each time the data model changes. It also adds data to new the database for testing purposes. This Initialiser class has to be called in the Application_Start() method in the .

Database Connection String

The Web.config file must be amended to include an additional connection string to the proposed database. The one shown below is for a local SQL Server database, although when the application is released this must be changed to a remote database server.

In the image above the connection string has been folded onto several lines for ease of reading. In the code itself, the connection string must be all on one long line.

The new connection string is called DerekWines in this example, and the database name is DP_Wines01.mdf Database names must be unique, so they are typically datetime stamped as is the DefaultConnection The database will not be created until a front end accessing some data from the database is added.

Web Forms Index