Working With ASP.Net Web Forms in Visual Studio 2013

Introduction

I provided a basic introduction to ASP.NET Web Forms in Visual Studio 2013 in ASP.NET Web Forms Introduction, therefore this article explains how to work with the Data Access Layer (DAL) class with the Entity Framework,  LocalDB and the Data Annotations in the ASP.NET Web Forms.

Working with Models

Here you will create the data models and use the entity classes in it. The Entity Framework is used as a reference to use the entity classes. The Entity Framework is an Object Relational Mapping (ORM) framework. We use it to reduce the data access code that we used to access the data. It provides the entity classes to access the data using LINQ.

There are various types of approaches in Entity Framework. We'll use the Code First Approach to define the data models by using classes. We'll map them to an existing database or use it to generate the new database.

Entity Framework Reference

The Entity Framework reference already exists in the references in the ASP.NET Web Forms Application. You can see that in the screenshot below:

Entity Framework Reference

If it is not present then it can be installed from the NuGet Package Manager. You must have a reference to the System.Data.Entity namespace to include the Entity Framework. It enables the classes to query, insert, update and delete the data. To install the Entity namespace, use the following procedure:

Step 1: Right-click on "References" and click on "Add Reference".

Adding Reference

Step 2: Select the System.Data.Entity and click on "Ok".

Adding Entity Reference

Entity Classes

We'll create the class to specify the schema of the data and such a class is called an Entity Class. We'll create properties here to designate the fields in our table in the database.

Use the following procedure to create the classes.

Step 1: In your Solution Explorer, right-click on the "Models" folder to add a class.

Adding Class in Models

Step 2: Enter the name of the class as "Cricketer".

Defining Class in Models

Step 3: Replace the class code with the code given below:

Add the following assembly:

using System.ComponentModel.DataAnnotations;

Code:

public class Cricketer

{

    [ScaffoldColumn(false)]

    public int CricketerID { get; set; }

   

    [Required, StringLength(100), Display (Name="Name")]

    public string CricketerName { get; set; }

   

    [Required, StringLength(50)]

    public string Team { get; set; }

 

    [Required]

    public string Grade { get; set; }

    public int? DetailsID { get; set; }

    public virtual Detail Detail { get; set; }

}

Step 4: Generate another class named Detail.

Add the following assembly:

using System.ComponentModel.DataAnnotations;

Then replace the class code with the following code:

public class Detail

{

    [ScaffoldColumn(false)]

    public int DetailsID { get; set; }

 

    [Required]

    public int ODI { get; set; }

 

    [Required]

    public int Test { get; set; }

    public virtual ICollection<Cricketer> Cricketers { get; set; }

}

Data Annotations

As you'd see above, some of the properties have the attributes designating the restrictions about the member such as [ScaffoldColumn(false)]. These are called data annotations. They specify the details and describe the validations for the user.

Context Class

We need to define the context class to use the classes for data accessing from the table in the database. Use the following procedure to add a context class.

Step 1: Right-click on the "Models" folder to add a new class.

Step 2: Enter the class name as CricketerContext.

Step 3:

Add the following assembly:

using System.Data.Entity;

Then replace the code with the following code:

public class CricketerContext : DbContext

{

    public CricketerContext()

        : base("WebFormsApplication")

    {

    }

 

    public DbSet<Detail> Details { get; set; }

    public DbSet<Cricketer> Cricketers { get; set; }

}

The class defined above represents the Entity Framework cricketer database context and to handle the storing and updating of the Cricketer class instances in the database.

Database Initializer Class

We'll provide some custom logic to initialize the database for running the first time the context is to be used. This will allow adding the seeded data to the database that represents the cricketer and details data.

Step 1: Add another class named CricketerDatabaseInitializer in the models folder.

Step 2:

Add the following assembly:

using System.Data.Entity;

Then modify your code with the following code:

public class CricketerDatabaseInitializer : DropCreateDatabaseIfModelChanges<CricketerContext>

{

    protected override void Seed(CricketerContext context)

    {

        GetDetails().ForEach(d => context.Details.Add(d));

        GetCricketers().ForEach(c => context.Cricketers.Add(c));

    }

 

    private static List<Detail> GetDetails()

    {

        var details = new List<Detail> {

            new Detail

            {

                DetailsID = 1, ODI = 463, Test = 200

            },

            new Detail

            {

                DetailsID = 2, ODI = 311, Test = 113

            },

            new Detail

            {

                DetailsID = 3, ODI = 344, Test = 164

            },

            new Detail

            {

                DetailsID = 4, ODI = 375, Test = 168

            },

        };

 

        return details;

    }

 

    private static List<Cricketer> GetCricketers()

    {

        var cricketers = new List<Cricketer> {

            new Cricketer

            {

                CricketerID = 1, CricketerName = "Sachin Tendulkar",

                Team = "India", Grade = "A", DetailsID = 1,

            },

            new Cricketer

            {

                CricketerID = 2, CricketerName = "Saurav Ganguly",

                Team = "India", Grade = "A", DetailsID = 2,

            },

            new Cricketer

            {

                CricketerID = 3, CricketerName = "Rahul Dravid",

                Team = "India", Grade = "A", DetailsID = 3,

            },

            new Cricketer

            {

                CricketerID = 4, CricketerName = "Rahul Dravid",

                Team = "Australia", Grade = "A", DetailsID = 4,

            },

    };

 

        return cricketers;

    }

}

The seed property is overridden and set after the initialization and creation of the database. The values from the details and cricketers display on the database. If we modify the database by changing the values through the code above, we'll not see the updated values after running the application because the code uses an implementation of the DropCreateDatabaseIfModelChanges class to recognize if the model has changed before resetting the seed data.

Now we have four classes that are created here. For example:

Model Classes

Application Configuration

Now, we need to configure the application to use the Model classes. There are two main sections given below:

  • Global File Configuration

    Open the Global.asax file.

    Add the following assembly:

     

    using System.Data.Entity;

    using WebFormsApplication.Models;

    Then modify the code with the following code:

    void Application_Start(object sender, EventArgs e)

    {

        // Code that runs on application startup

        RouteConfig.RegisterRoutes(RouteTable.Routes);

        BundleConfig.RegisterBundles(BundleTable.Bundles);

        Database.SetInitializer(new CricketerDatabaseInitializer());

    }
     

  • Web Config File Configuration

    Open the Web.config file and add the following in the connection string:
     

    <add name="WebFormsApplication" connectionString="Data Source=(LocalDb)\v11.0;
         AttachDbFilename=|DataDirectory|\WebFormsApp.mdf;
         Integrated Security=True
    "

         providerName="System.Data.SqlClient" />

Build Application

Please build your solution to ensure that there are no errors in your application.

Building Solution

Summary

This article will help you to learn and create the data model and data annotations in the ASP.NET Web Forms Application. You can also configure the application to use the data models to run the application. We'll fetch the data and work on the User Interface in my next article. Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all