Skip to main content

Entity Framework Explained


Entity Framework Explained


What is Entity Framework?


Before the advent of .NET 3.5, we (developers) often used to write ADO.NET code or Enterprise Data Access Block to save or retrieve application data from the underlying database. We used to open a connection to the database, create a DataSet to fetch or submit the data to the database, convert data from the DataSet to .NET objects or vice-versa to apply business rules. This was a cumbersome and error prone process. Microsoft has provided a framework called "Entity Framework" to automate all these database related activities for your application. Retrieved from Entity Framework site.

Entity Framework is an open-source ORM framework for .NET applications supported by Microsoft. It enables developers to work with data using objects of domain specific classes without focusing on the underlying database tables and columns where this data is stored. With the Entity Framework, developers can work at a higher level of abstraction when they deal with data, and can create and maintain data-oriented applications with less code compared with traditional applications.

Official Definition: “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.”

ORM (Object Relational Mapping)


Object-relational mapping (ORMO/RM, and O/R mapping tool) in computer science is a programming technique for converting data between incompatible type systems using object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to construct their own ORM tools. From wikipedia.




Entity Framework approaches


There are mainly two types of approaches allows by EF. They are Database-First and Code-First (the first being absent from EF Core (7), but still valid up to version 6.1.3).
The difference between the two approaches is that Database-First, we  are modelling a pre-existing  database and derive our objects from its tables, while in the Code-mode First, we create our models and their respective properties representing the table fields to determine the structure of the database.

In our previous article, Database Driven Web App Tutorial with ASP.NET MVC using Model First Approach, we use model first approach, where we created the Guest Model first and the table fields were created thereafter from the model properties.

Why Entity Framework?

Entity Framework is an ORM and ORMs are aimed to increase the developer’s productivity by reducing the redundant task of persisting the data used in the applications.
·        Entity Framework can generate the necessary database commands for reading or writing data in the database and execute them for you.
·        If you're querying, you can express your queries against your domain objects using LINQ to entities.
·        Entity Framework will execute the relevant query in the database and then materialize results into instances of your domain objects for you to work within your app.
There are other ORMs in the marketplace such as NHibernate and LLBLGen Pro. Most ORMs typically map domain types directly to the database schema. As stated by TutorialPoint.


Database First Approach

Let’s look at the Entity Framework Database First Approach step by step
Create a new Project from Visual Studio as shown below

Select the MVC application and click on Create button for Visual Studio to create MVC application as shown below

Right klick on Models folder, select Add then New Item as shown below

In Add New Item Dialog Window, Click on Data on left side of the window that show installed. After that, select ADO.NET Entity Data Model enter the name of the model as csharpnaija or anything you want and click on Add button as shown below
In Entity Data Model Wizard, select EF Designer from database and click on Next as shown below


In Choose your Data Connection window, either select or Create a new Connection, in our case, we are creating new connection

Click on New Connection
In the Connection Properties Window, Enter Server name, select authentication type (Windows or SQL Authentication), select database to work with, finally, click on Test Connection to see if the connection is established, if successful, then click on OK as can be seen below

Click on Next to select the tables needed


Click on Finish button to create the edmx file in the Models folder and the visual studio will add the required references automatically as shown below



From the above image, we can now see that the two tables we created in our previous article are now generated as model classes with the fields being properties of the classes as shown below.




One – to – Many relationship is automatically implemented by the Entity framework as shown from the two tables. We will dwell more on relationships in subsequent article.
                        
Let us now add a controller class to a controller folder to see how we can add, delete, edit and list an Employees records from employees table.
Right click on controllers, select Add and click on controller as shown below

Now select MVC 5 Controller with views, using Entity Framework and click on Add as shown below



In the Add controller window, select model class you want to use, Data context class leave the remaining fields are default and click on Add as shown below




After we clicked on the Add button as above, a controller class will be created with some action methods for Listing the employee records (Index method), for individual details (Details method), adding new employee (Create method), Editing employee record (Edit method) and finally deleting an existing employee (Delete method).







All the above codes are writing for us automatically using the employees table from our database and converting it to class.

Now build the application and shown below




If build is successful or not the out window will show the status as shown below


Now let us add a link to our shared view for display on the menu bar
Expand Views folder, next expand Shared folder as shown below

Now double click on the _Layout.cshtml file to open it

Add an another actionlink below the Home and click on Save button or press ctrl S as shown below

Run the application by click on the run button

The application will display Home page as shown below

Click on Employees link on the menu bar to List all employees as shown below

Comments

Popular posts from this blog

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

Most Popular Programming Languages in 2020

Most Popular Programming Languages in 2020 In this blog post, you will learn about the most popular programming languages in 2020 for creating the best web applications. Check its pros and cons. Analyzed by technostacks Not very long ago, just a few people were considered to be computer programmers, and the general public viewed them with awe. In this digital age that we are now living in, however, a large number of IT jobs need a solid grasp of one or more programming languages. Whether one wants to develop a mobile app or get a certification for having programming knowledge, or even to learn new skills, one needs to opt for the right programming language. Below mentioned eight most popular programming languages which are in demand for software development and web applications. This is the most used programming languages in 2019 and will be in 2020. For each, there is little information about the language, benefits and its complexity, as well as about its usage. One must...

HashTable in C# with Example

  HashTable in C# with Example Hashtable  is used to store a collection of key/value pairs of different  data types  and are organized based on the hash code of the key.   Generally, the hashtable object will contain buckets to store elements of the collection. The bucket here, is a virtual subgroup of elements within the hashtable and each bucket is associated with a hash code, which is generated based on the key of an element.   In C#, hashtable is same as a  dictionary  object but the only difference is that the  dictionary  object is used to store a key-value pair of same  data type  elements.   When compared with  dictionary  object, the hashtable will provide a lower performance because the hashtable elements are of object type so the boxing and unboxing process will occur when we are storing or retrieving values from the hashtable.   C# HashTable Declaration Hashtable is a non-generic type...