VIEW ARTICLE

Entity Framework Database-First Approach in ASP.NET MVC

Author: Suresh Kr Chaudhary
Category: Programming
Submitted On: 9/7/2017
Published On: 9/7/2017
ABSTRACT: This article describes practical steps involved in the implementation of Entity Framework Database-First approach in any ASP.NET MVC based program.

Entity Framework - An Introduction

As per Microsoft defeinition, Entity Framework is an object-relational mapper (O/RM) that enables .NET developers to work with a database using .NET objects. It eliminates the need for most of the data-access code that developers usually need to write.

Entity Framework 6 (EF6) is a tried and tested data access technology with many years of features and stabilization. It first released in 2008, as part of .NET Framework 3.5 SP1 and Visual Studio 2008 SP1. Starting with the EF4.1 release it has shipped as the EntityFramework NuGet package - currently one of the most popular packages on NuGet.org.

Entity Framework allows you to create a database model by writing code or using boxes and lines in the EF Designer. Both of these approaches can be used to target an existing database or create a new database.

Another approach is to recreate the database model in Entity Framework designer by just fetching real schema entities from the database, and such this approach is called as Database-First approach. We shall bediscussing this approach in this article.

If you have an existing database and quite a number of database entities already defined in the database schema, and you would like to use this DB schema to create a model in your DOTNET program so that you could use the underneath database efficiently, EF comes to your assistance. It provides smooth operations of creation of the model from the database, creating corresponding data entities called as DOTNET entities that we can use easily in our program controllers and Server side code.
In the following sections, major steps in implementing Entity Framework database first approach, are discussed.

Database Underneath

Build a database schema by creating tables, primary key, unique keys, indexes, composite keys, relations between tables, constraints etc. and perform a general testing that created database schema is in its best possible shape as per current middleware requirements.

Note: The term "schema" refers to the organization of data as a blueprint of how the database is constructed (divided into database tables in the case of relational databases).

Database Schema

SQL-Database to Link Mapping

Database Schema EF Link Mapping

The Entity Framework when implemented established a mapping between dotnet objects being used in the program and the real entities in database. This makes it easier to manipulate objects in an object oriented manner and develop software in a rapid manner.


Creating an Entity Model

To create an Entity framework setup in your program, in the Visual Studio, open the designated project, right-click on the Model folder and Add "ADO.NET Entity Framework Model" and provide its name.

Select the database, that gives you options to select the objects therein. You select the tables and related objects to be included in the Entity Diagram. Once you select the required objects from database and proceed, framework automatically creates the corresponding objects in the program and maps them to the database objects.

Entity Model

It introduces YourModel.edmx sub-folder, and within that another sub-folder YourModel.tt that contains multiple files with .cs extension. Each of these files represent an object that corresponds to the database table. A typical .cs file looks like the following: -


namespace YourProgram.Models
{
    using System;
    using System.Collections.Generic;
    
    public partial class LibraryBook
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public LibraryBook()
        {
            this.Bookmarks = new HashSet();
            this.Tags = new HashSet();
        }
    
        public int BookID { get; set; }
        public string Title { get; set; }
        public string TitleName { get; set; }
        public int SectionID { get; set; }
        public Nullable CategoryID { get; set; }
        public Nullable AuthorID { get; set; }
        public string BookFile { get; set; }
        public string BookBrief { get; set; }
        
        public virtual Category Category { get; set; }
        public virtual Section Section { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection Bookmarks { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection Tags { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
      
    }
}

The object structure is automatically built as per your schema in the database. Virtual properties and collections represent relations amongst tables etc with constraints.

Once the diagram is ready, you compile the program without any error(s), you are ready to use EF objects in your program through high level LINK language.

Creating MetaData

In the Model sub-folder, create a file with the name like MetaData.cs, and define metadata for the objects. Usually we define metadata in the partial class with the same name as of the object class but with MetaData word appended to it.

Next step is to link this metadata with the main object. This is done by adding another file with the name say PartialClasses.cs under the Model sub-folder. Within this class we define metadata type of class Metadata (that we defined above) followed by the partial class of the orinal object.

Note: We shall discuss exact steps to create and implement metadata in another article soon. Stay tuned.

Changing or Updating from Database

When you change something in the database, it becomes a necessity to reflect those changes in the program, so as to enable smooth operations. After having changes done in the database, the ideal steps involved in the process are as follows: -

  • Go to the EF diagram first, select corresponding EF object and remove it from the model.
  • Right click in the EF diagram and select "Update from Database"
  • Select Add required tables/objects from the dialog box and proceed.
Compile the program again and you are ready for running...

Just to highlight that Tesarrow uses Entity Framework Database-First approach in many of its commercial products, and it has been proved as a successful strategy for enterprise level large scale programs.


Go to Top
Entity Framework Database-First Approach in ASP.NET MVC

Related Questions...(0) Ask A Question

Ask a Question

Go to Top