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

Collections in C#

Collections in C# In our previous article , we have learned about how we can use arrays in C#. Arrays in programming are used to group a set of related objects. So one could create an array or a set of Integers, which could be accessed via one variable name. What is Collections in C#? Collections are similar to Arrays, it provides a more flexible way of working with a group of objects. In arrays, you would have noticed that you need to define the number of elements in an array beforehand. This had to be done when the array was declared. But in a collection, you don't need to define the size of the collection beforehand. You can add elements or even remove elements from the collection at any point of time. This article will focus on how we can work with the different collections available in C#. There are three distinct collection types in C#: standard generic concurrent The standard collections are found under the System.Collections. They do not store elemen...

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

System.IO Namesapce in C#

  System.IO Namesapce in C# A  file  is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a  stream . The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the  input stream  and the  output stream . The  input stream  is used for reading data from file (read operation) and the  output stream  is used for writing into the file (write operation). From the above definition of file, the C# provides a namespace that enable us to manipulate file in C# called System.IO.   System.IO  is a  namespace  and it contains a standard IO (input/output) types such as classes , structures , enumerations , and  delegates  to perform a read/write operations on different sources like file, memory, network, etc.   System.IO Classes The table below shows differen...