An entity framework (EF) is a technique to establish a connection to a database and use the objects of that database. The EF makes it easy to perform most routine operations of a database. For example, you can manually select the objects you need for your database. You can visualize the relationships among those objects, and you can visually maintain your database. In short, the EF tremendously reduces the amount of code you need to write for your database project. The EF consists of a technique that uses existing .NET Framework classes and Microsoft Visual Studio to assist you with your database project in ASP.NET MVC.

To support the entity framewoek, the .NET Framework provides a namespace named System.Data.Entity.

There are various ways you can use the EF.

Practical
Learning: Introducing the Entity Framework

Start Microsoft Visual Studio

On the main menu, click File -> New -> Project...

In the New Project dialog box, click ASP.NET Web Application (.NET) and change the project Name to CeilInn1

Click OK

In the New ASP.NET Web Application dialog box, click the MVC icon and click OK

In the Solution Explorer, right-click Models -> Add -> New Item...

In the left frame of the Add New Item dialog box, click Data

In the left frame of the Add New Item dialog box, click Data and, in the middle frame, click ADO.NET Entity Data Model

Change the Name to CeilInnModel

Click Add

In the first page of the Entity Data Model Wizard, click Empty Code First Model

Click Finish

A Class for a Table

When using the entity framework, you need a C# class for each table of the database you will use. You can first create a database with its tables and then ask Microsoft Visual Studio to generate a class for each table. You can first create a (the) class(es) for a table or each table, then use Microsoft Visual Studio to create a database that will contain (a) table(s) based on the class(es).

A class used in the entity framework primarily resembles a normal C# class. The class must contain an automatic property for each column of the table; that is, the columns of a table that exist already or the columns for a table that will be created. Usually in SQL, the name of a table is in plural while in C#, the name of a class is singular. Here is an example of a class that would be used for a database table:

This type of class (is used to create an object that) represents a record of the equivalent table in the target database. The entity framework needs a class that relates that object to the actual data in the database. That EF class represents a record of its equivalent table in the database. This makes the class able to create records, select records, and maintain (edit/update and delete) records. To support these operations, the System.Data.Entity namespace provides a class named DbContext. It implements the IDisposable interface:

public class DbContext : IDisposable, IObjectContextAdapter

To use the DbContext class, derive a class from it. When the time comes, you or Microsoft Visual Studio will create a connection string in the Web.config file. The name you give to your DbContext-derived class is (must be) the same name of the connection string. Here is an example of deriving a class from DbContext:

The DbContext class provides a property for each of the DbSet classes. In your DbContext-derived class, you must create a DbSet property for each class that represents a table. In most cases, you should use the generic class. In this case, pass the name of your table class as the parameter type. The name of the property should be in plural, which would be equivalent to the name of the table. Here is an example:

To let you get access to a database, the System.Data.Entity namespace provides a class named Database. To give you access to the database to which the entity framework refers, the DbContext class is equipped with a property named Database of type Database

public Database Database { get; }

As a result, to have access to the database of your project, in your controller class, declare a variable of your DbContext-based class. Of course, you must be using the namespace of the model document. Here is an example:

This declaration gives you access to the DbSet<> object of the property you created. As you might have noticed, the DbSet class implements the IEnumerable<> interface. This means that its list of records can be converted to a List<> collection by calling its ToList() method.

The DbSet<> class implements the IQueryable<> interface. This means that its object gets all the LINQ functionalities.

Creating a Modeled Database: Starting from One or More Classes

Introduction

One way you can use the entity framework is to first create one or more C# classes in your project, then ask Microsoft Visual Studio to create a database that contains one or more tables based on the class(es) you had created. To make your job easier, start by creating an ADO.NET Entity Data Model for a non-existing database. This would cause Microsoft Visual Studio to create a class derived from DbContext and get it ready for your project.

Creating the Table Classes

When you use the Empty Code First Model option of the Entity Data Model Wizard, you indicate that you want the entity framework to prepare a database for you. At that time, Microsoft Visual Studio creates an empty database file for you. It also adds a connection string in your root Web.config file. The name of the connection string is the name you had provided when creating the ADO.NET Entity Data Model. Microsoft Visual Studio also creates a file that contains a class derived from DbContext. The name of the class is the name you had provided when creating the ADO.NET Entity Data Model, which is also the name of the connection string. You can change one of the names but you must also change the other to be the same. This means that if you change the name of the class, you must apply that same name to the connection string and vice-versa.

Once Microsoft Visual Studio has created a DbContext-based class for you, you can create the necessary class(es) for the table(s) of your database. Every table of your database must have a primary key. Since you start the project from at least one class (the class(es) you create after Microsoft Visual Studio has prepared the project for you), the class must indicate what property will serve as the primary key. In fact, every one of the classes you will create must indicate which one of its properties represents the primary key of its future table.

If you are creating a class for a database table, to indicate the property that holds the primary key, we saw that you can mark the necessary property with the KeyAttribute attribute.

Practical
Learning: Creating a Class for a Table

Notice that a file named CielInn1Model.cs displays.
Change the document as follows:

To prepare the context, on the main menu, click Build -> Build Solution

Creating a Database Controller

As always, in order to use a database in your project, you must use a controller. Before creating the controller class, you must first build the solution. If the build is successful, create a controller that supports the entity framework. This would open the Add Controller dialog box. In the Model Class, select the option that has the name of the class and model in parentheses. In the Data Context Class, select the option that has the name of the DbContext-based class and the model in the parentheses.

When you create a controller that uses the entity framework, Microsoft Visual Studio adds all the necessary methods and associated views used to create, read, edit, and delete records.

Adding Records Through the Entity Framework

To let you add a record to the data context, the DbSet<> class is equipped with a method named Add. Its syntax is:

public virtual TEntity Add(TEntity entity)

When calling this method, you can simply pass an object of your table class. After calling this method, you can use its view to create a record. To do this:

From the solution Explorer, right-click the Create.cshtml and click View in Browser (Internet Explorer)

When creating a class for a table, you can specify that you want the user to enter a certain minimum number of character in the corresponding text box. To support this, the System.ComponentModel.DataAnnotations namespace provides an attribute named MinLength. When applying this attribute to a property in a class, add the parentheses to it and enter the desired number in the parentheses.

The Maximum Number of Characters

As seen in our introduction to text-based fields, databases support a maximum number of characters for a column. We have already seen many examples of how to specify this number in the parentheses of CHAR, VARCHAR, NCHAR and NVARCHAR. To let you specify the maximum number of characters that a column can hold, the System.ComponentModel.DataAnnotations namespace provides an attribute named MaxLength. This attribute is used or applied like its MinLength counterpart.

To let you specify both the minimum and maximum number of characters for a field, the System.ComponentModel.DataAnnotations namespace provides an attribute named StringLength. To support the minimum string length, the StringLengthAttribute class is equipped with a property named MinimumLength. To use it in a class, apply it to a proproperty and add parentheses to it. In the parentheses, assign the desired value to MinimumLength. The he StringLengthAttribute class also supports a maximum number of characters through a property named MaximumLength. It is used like its counterpart.

A Required Property

If you are creating a class that will be used in an entity framework, to let you indicate that the user must provide a value for the corresponding column of the table, the System.ComponentModel.DataAnnotations namespace provides an attribute named Required and that is reqpresented by the RequiredAttributre class.

To indicate that the user must provide a value for a column, mark its property with the Required attribute. Here are two examples:

By default, when the value of a column displays, the database engine uses the name of the column to indicate the presence of the field. Some names are not very appropriate. The string that represents a field is referred to as its caption. Fortunately, you can set the caption to anything you want.

To assist you with the caption of a field, the System.ComponentModel.DataAnnotations namespace provides an attribute named DisplayAttribute. One of the properties of this attribute is named Name. The specify the caption of a field, assign the desired string to this property.

In the Solution Explorer, expand App_Start and double-click BundleConfig.cs

Change the document as follows:

using System.Web.Optimization;
namespace BethesdaCarRental1
{
public class BundleConfig
{
// For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css",
"~/Content/BethesdaCarRental.css"));
}
}
}

A Controller to Create and Manage Records

The entity framework make it particularly easy to create views that are connected to the appropriate tables of a database. This is done by creating or generating a controller for each class that was created for the tables.