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. The Entity Framework reference already exists in the references in the ASP.NET Web Forms Application. You can see that in the screenshot below:

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".

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.

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

 

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 = "yourname",

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

            },

            new Cricketer

            {

                CricketerID = 2, CricketerName = "Saurav Ganguly",

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

            },

            new Cricketer

            {

                CricketerID = 3, CricketerName = "
yourname",

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

            },

            new Cricketer

            {

                CricketerID = 4, CricketerName = "
yourname",

                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:

 

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" />