Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Entity Framework Essentials

4.88/5 (14 votes)
20 Dec 2020CPOL7 min read 11.7K  
Entity Framework database
This article discusses the essentials of Entity Framework. We will discuss Connection without using Entity Framework, Database First Approach, Users Model Approach and the Model First Approach.

Introduction

In this article, I would like to show you the essentials of Entity Framework. For connecting your application with a database, you can use a framework. Using a framework allows you to upload your object and save it in a database. Of course, you can create a connection without any framework, but you should realize classes such as:

  • sqlConnection
  • sqlDataReader
  • sqlCommand

Moreover, you can create your framework, but it could involve a lot of cost and it is not reasonable. You could waste a lot of time and write tonnes of code for realization, for example, stored procedures, using ADO.NET objects and mapping.

Connection Without Using Entity Framework

Entity Framework allows you to not care about these things. Let's try and make a database connection without a framework. Connect to database:

Image 1

Image 1 - Database for connect

Let's create a new console application and add in this project. In App.config file, add connectionString:

XML
 <connectionStrings>
        <add name="DbConnect"
            connectionString="Data Source=LAPTOP-0QQLJ858\SQLEXPRESS;
            Initial Catalog=HelpDesk;Integrated Security=True"
            providerName="System.Data.SqlClient" />
</connectionStrings>

Here, you need to change connectionString to your Data Source.

Then, add simple code:

C#
using (IDbConnection connection = new SqlConnection(Settings.Default.DBConnect))
            {
                IDbCommand command = new SqlCommand("Select * FROM Users");
                command.Connection = connection;
                connection.Open();

                IDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine("ID: {0}\t Name:{1}",
                                       reader.GetInt32(0),reader.GetString(1));
                }
            }

As a result, what we have is:

Image 2

Image 2 - Result of connecting to database

But here, we have a lot of difficulties:

  1. We have SQL code in C# code. We are using as String, as a result, we can make a mistake very easily. Moreover, we can't make refactoring.
  2. We use untyped dataset. For example, we use Execute reader and we are not sure what is inside this reader. Using "GetInt32(0)" and GetString(1), we must know in advance that we are using exactly these data types. Terrible.
  3. Every time when we want to create a connection, we must know when to open the connection and close the connection.

Of course, we can write data from database in a class, but it will not fix those problems. It is much more convenient to use an ORM framework, one of them is Entity Framework.

Entity Framework has 3 approaches.

Database First Approach

Database first - we create the database first, then the Entity Framework will generate the classes based on the database. This is a popular approach that has been used by developers for many years.

First of all, we create a database in MS SQL Management Studio and then, for our example, create a table named "Users" with columns name and their data type as shown in the image below:

Image 3

Image 3 - Creating Users table

Don't forget about primary key and Identity Specification.

In this approach, we cannot make changing history. If somebody has made changes, we can't follow it.

Move on to MS Visual Studio and create a console application. Then, connect Entity Framework in Nuget Packages.

Image 4

Image 4 - Connecting Entity Framework

Then add a new item (ADO.NET Entity Data Model) in the project.

Image 5

Image 5 - Adding ADO.NET Entity Data Model

In the next step, choose EF Designer from database.

Image 6

Image 6 - Creates a model in the EF Designer

Then tap on the New Connection and choose your database server and the database that was created earlier.

Image 7

Image 7 - Creating New Connection

In the next step, if a previous step was correct, you would choose table, which will connect using Entity Framework. In this example, it is Users table and Model Namespace: UsersModel.

Image 8

Image 8 - Enitity Data Model Wizard

After this step, Entity Framework will create classes and diagrams. In this example, we will have User.cs with code:

C#
namespace UsersDBFirst
{
    using System;
    using System.Collections.Generic;
    
    public partial class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public System.DateTime CreateData { get; set; }
    }
}

It describes your database. Also, we have User's Context.cs, the code for which is:

C#
public partial class UsersEntities : DbContext
    {
        public UsersEntities()
            : base("name=UsersEntities")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet<User> Users { get; set; }
    }

This class implements DbContext interface and includes public virtual member - DbSet which realises connection with dataBase. Basically, we are ready for writing and reading data from database. Write a simple code in the main function:

C#
static void Main(string[] args)
        {
            using (UsersEntities db = new UsersEntities())
            {
                User user = new User() 
                { Name = "Jo",CreateData= DateTime.Now, Email = "Jo@gmail.com" };                
                db.Users.Add(user);
                db.SaveChanges();
            }
        }

And we have a result in MS SQL Management Studio changes in table.

Image 9

Image 9 - The result in MS SQL Management Studio

A lot of developers got used to this approach. It makes sense, but we can't log changes in structure database.

Code first Approach

Let's consider the code first approach. Using code first, we create the main classes first, then the Entity Framework generates database tables based on these classes.

First of all, create console application and connect Entity Framework in the project. Then add classes: UserModel and UsersContext.

In UsersModel, write code:

C#
class UsersModel
   {
       [Key]
       public int Id { get; set; }
       public string Name { get; set; }
       public string Email { get; set; }
       public DateTime DateCreate { get; set; }
   }

In UsersContext, write code:

C#
class UsersContext: DbContext
 {
     public virtual DbSet<UsersModel> Users { get; set; }
 }

Of course, if you have more entities in your project, you have to add in Context class.

Move on in the project properties and setup connection strings. Here, choose database server and database name.

Image 10

Image 10 - Setup connection string

In app.config file, you should have similar code:

XML
<connectionStrings>
       <add name="UsersContext" connectionString="Data Source=.\SQLEXPRESS;
        Initial Catalog=UsersDBCodeFirst;Integrated Security=SSPI"
            providerName="System.Data.SqlClient" />
</connectionStrings>

In Code first approach, we use migrations. Move on in Package Manager console and write the command:

enable-migrations

Every time when we change models, we have to use migrations. Let's write in Package Manager command:

add-migration CreateUsers

As a result, we have a new file 202012010405502_CreateUsers.cs which includes date and time in the name, also it has code:

C#
public override void Up()
        {
            CreateTable(
                "dbo.UsersModels",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        Name = c.String(),
                        Email = c.String(),
                        DateCreate = c.DateTime(nullable: false),
                    })
                .PrimaryKey(t => t.Id);            
        }
        
        public override void Down()
        {
            DropTable("dbo.UsersModels");
        }

Let's start migration and write "update-database" in Package Manager. If you did all steps correctly in the MS SQL Server Management Studio, you will have a new database.

Image 11

Image 11 - Table was created using Code first approach

If you update data, you don't need to use migrations. Let's write similar code:

C#
using (UsersContext db = new UsersContext())
            {
                UsersModel user = new UsersModel() 
                { Name = "Jo", DateCreate = DateTime.Now, Email = "Jo@gmail.com" };
                db.Users.Add(user);
                db.SaveChanges();
            }

As a result, we have data in the table.

Image 12

Image 12 - The result of add data in the table

This approach appeared later, but is also quite popular among developers. With the help of the migration mechanism, you can create logs of your database changes.

Model First Approach

The third approach is Model First. Model First introduces yet another approach to working with the Entity Framework. The essence of this approach is that first a model is made, and then a database is created from it.

Let's create a new project of the Console Application type. Don't forget about connect Entity Framework. Then add a new item to the project. And then, in the Add New Item window, select ADO.NET Entity Data Model:

Image 13

Image 13 - ADO.NET Entity Data Model

Since the model will describe a person, let's call it User. Click OK and the model creation wizard will open. In here, choose Empty EF Designer model. The model wizard looks like the image below:

Image 14

Image 14 - Entity Data Model Wizard

Press the Finish button, and an empty window for creating a model will open before us.

Image 15

Image 15 - Empty Diagram

Using Toolbox, move element named entity on board. Then, using right click on the model and choosing "Scalar property", add elements on the diagram. Here, we should have a diagram like the image below:

Image 16

Image 16 - User's diagram

Be careful, because all new properties have data as string. Just switch as DataTime type in CreationData property. After Creation diagram using option "Rebuild", rebuild your project. Now using this model, we can generate code and database. The first lets us generate model's code. For this, choose Add Code Generation Item.

Image 17

Image 17 -Add Code Generation Item

Then, we have to choose Entity Framework version, choose 6x. After that Entity Framework, generate Model file - Users.cs with code:

C#
public partial class Users
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public System.DateTime CreationData { get; set; }
    }

Also, we have context file UsersModel.Context.cs with code:

C#
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

public partial class UserModelContainer : DbContext
{
    public UserModelContainer()
        : base("name=UserModelContainer")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<Users> Users { get; set; }
}

Now let's generate a database for our model. So, right-click on the model diagram and select Create database from model (Generate database from model) from the drop-down list. A wizard for creating a connection will open before us.

Image 18

Image 18 - Generate Database Wizard

Let's create a New Connection. Here, indicate your database server and database name.

Image 19

Image 19 - Connection Properties

After that, the database script will be generated by Entity Framework:

Image 20

Image 20 - Generate Database Wizard

Click on Finish. We will automatically open the User.edmx.sql script file in Visual Studio. And finally, we will need to run this script. To do this, click on the green Execute button in the upper left corner:

Image 21

Image 21 - SQL script

Let's write some code:

C#
using (UserModelContainer db = new UserModelContainer())
            {
                Users user = new Users() 
                { Name = "Jo", CreationData = DateTime.Now, Email = "Jo@gmail.com" };
                db.Users.Add(user);
                db.SaveChanges();
            }

Here, we have database structure.

Image 22

Image 22 - Structure of database

Also, we have the record in the database image below:

Image 23

Image 23 - Record in the database

Conclusion

In conclusion, I want to say that the database first approach is more suitable. Although it does not matter which methods you use, I just wanted to show that Entity Framework is not complicated and, by a similar principle, you can use it in your more complex applications.

History

  • 3rd December, 2020: Initial version
 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)