Code First Example – Entity Framework

In this tutorial let us create a simple Entity Framework Code First Example application. We learn what is Entity Framework in the previous tutorial. In this article, we will show how to build a simple code first console application. We will show you how to create a simple entity. We will also show you how to perform simple CRUD operations on that entity and persist the entity to the database.

Link to all Entity Framework Tutorial  articles

Software Versions used in the tutorial

  • Visual Studio 2015
  • Entity framework 6.2.0.
  • .NET 4.5
  • C#

What is Code First

In the Code First approach, you manually create the entity domain model (EDM) classes in your application. The database is created from these classes. This gives you the direct control of what is being generated in the database. The Visual model designer is not used in the code first approach. Code First follows the Domain-Driven Design (DDD) principles.

In this tutorial, we will create a simple application with a user class.  Our user class will have basic information like name and email address of the user.

Create the Code First Example Project

  1. Open Visual Studio.
  2. File ->New -> Project
  3. Select Template -> Visual C# -> Windows
  4. Select Console Application
  5. Name the application as “EFGettingStarted”
  6. Click on OK
Entity Framework Code First Example. Create new project

Installing Entity Framework

The next step is to install the Entity framework. This can be installed via NuGet package console. Click on Tools->Nuget Package manager -> Package Manager Console and type the following command

Installing Entity Framework

This will install the latest version of the Entity Framework (6.2.0).

Entity Type

The next step is to create the Entity Data Model (EDM)

  1. Select the Project
  2. Right click and click on add -> Class
  3. Name the class as Model.cs
  4. Copy the following code to the model.cs

We are done with our entity model.

DBContext

The DbContext (often referred to as context) is the class which is responsible for interacting with the entity model and the data store. It allows you to query, insert, update and delete operations on the entities. This class is derived from the system.data.entity.dbcontext namespace. The older version of the entity framework used objectContext. DbContext is actually a wrapper around the objectContext class.

The DBContext is the heart of the Entity Framework. It has several responsibilities. It Manages the database, Manages database connections, creates & initializes the database. It queries for data and converts them models by using the process called materialization. It keeps track of the added, modified & deleted entities in the memory and updates the database when asked for.

You can read more about what is dbcontext in entity framework

Creating the Context

You can add a DbContext in your project by creating a class which derives from the DbContext class

  1. Select the Project
  2. Right Click -> Add -> Class
  3. Name the class as EFContext.cs
  4. Click on Add
  5. Import the namespace System.Data.Entity
  6. Make the EFContext class as public and inherit it from the DbContext class

Now we have added the Context class EFContext to our project

DBSet

As mentioned above DbContext class exposes the generic version of DbSet which represents the collection of entities (entity set). Each entity type must expose the DbSet property so that they can be used in CRUD Operations

DbSet provides the methods to manage the entity set. To Add DbSet Property to your class add the following in the context class

Finally, our EFContext class looks like this

Adding data

We have defined our model (user class) and the context (EFContext). Now it is time to create a new user

Open the program class. In the main method of the class, paste the following code

In the above code, we created a new user instance.

Then, we created an instance of the DbContext object. 

The DbContext returns the Users Entity set (DbSet<TEntity>). We invoked the add method of the Users object and passed the newly created user instance.

Finally, we invoked the SaveChanges method of the DbContext object to save the changes to the database.

Now we are ready to test our application. Open the Main method of the program class and add the following code.

Run the Application. If everything is ok then you should see “press any key to close” message. Press any key and console window will close.

Read More:
Add Records in Entity Framework

Where is the database

We have not defined our database connection string. The EF is smart enough to discover and create the database for us. The EF uses a series of steps to discover and initialize the database. The Process is also called as database initialization.

In the absence of any Connection String provided in the app.config file, the EF creates the database either in localdb or SQL Express depending on the system. 

In Visual Studio go to View->SQL Server Object Explorer option.

Under SQL Server, you should be able to see either (localdb)\V11.0 or (localdb)\MSSQLLocalDB. Expand the nodes and you will see that the database by the name “EFGettingStarted.EFContext” is created.

Code First in Entity Framework
Code First in Entity Framework

As you can see from the above image, Entity Framework has created users table with the column for each property. Few important things to note that

  1. The Database was automatically created by EF
  2. Name of the database is “EFGettingStarted.EFContext”, which is the fully qualified name of the DbContext class
  3. The Table names are pluralized. Our Entity class name was User. The Table name is Users
  4. Column UserID is automatically configured as Primary Key.
  5. The UserID is also configured as the identity column

The Code First does this by using Code-first conventions. It uses the model to create the database and build the tables and columns of the tables.

Querying the data

The next option is to query the data.

The querying is done by the find method, which takes the Primary key(s) as the argument and retrieves the matching row from the database and populates the entity. 

Next, we check the returned entity for null & display the result

Open the program.cs and copy the following code

Read More:
Querying in Entity Framework

Editing the Data

Next, let us try to edit the entity

To Edit and entity, we need to get the entity from the database using the find method

Next, Modify the desired fields

Finally, call saveChanges to update the database;

Read More :
Update Records Entity Framework

Deleting the data

To Delete the entity, first use find method the get the entity. Then use the Remove method to remove it from the context. Finally call the savechanges method to update the database

Read More:
Delete Records Entity Framework

References

  1. DbContext
  2. DbSet
  3. Querying in Entity Framework
  4. Add Records
  5. Update Records
  6. Delete Records

Summary

In this tutorial, we have created a simple code first example application to demonstrate the CRUD operation on users entity. We learned how to create a model. learnt how to create the Dbcontext class and create DBSet property of the model. Finally, we implemented a simple CRUD operations using console application.

Download

Source Code

4 thoughts on “Code First Example – Entity Framework”

  1. When I paste the code into my Program.cs file, I get an error in my ctx.Users.Add(usr); line. The error is under the Users and it says EFContext.Users is inaccessible due to its protection level. I’m not sure what is going on because everything in my Model.cs is public like in the example.

    1. Is your DbSet in EFContext.cs also public as well? I only ask because I was getting the same error, and that turned out to be my problem.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top