Introduction to Entity Framework Core

Entity Framework (EF) Core is a lightweight, extensible, open-source, and cross-platform version of the popular Entity Framework data access technology. EF Core can serve as an object-relational mapper (ORM), enabling .NET developers to work with a database using .NET objects, and eliminating the need for most of the data-access code they usually need to write. EF Core supports many database engines. In this article, I will teach you how to connect with SQL Server from ASP.NET MVC using Entity Framework Core.

Before we dive deep into the lesson I want to teach you some basics. It’s better to have some basic understanding of these things to understand the bigger picture that we are going to learn.

Object Relational Mapper (ORM)

The ORM frameworks generate objects (as in Object Oriented Programming) that virtually map the tables in a database. Then the programmer uses these objects to interact with the database. So the main idea is to try and shield the programmer from having to write optimized SQL code. For example, we are writing an application in C# and our database is in SQL. They are different platforms and have different formats right. How can they communicate with each other then? We need middleware to connect these two. ORM automatically maps data with the relevant classes in the program when we are trying to retrieve the data from the database or else to insert the object that we created to the database it will automatically translate to the code that SQL understands and add it to the database. Entity Framework Core also uses this ORM.

Image for post
Image for post

What did people do before ORM?

· Programmers had to write code for maintaining the connection to the database.

· They had to design domain classes inside the program, manually according to the database schema.

· Take the data from the database and remap it according to the class objects.

· Saving the data back to the database from the application also needs the same kind of process.

ORM Frameworks that are available in .NET

Image for post
Image for post

Entity Framework and Core history

Image for post
Image for post

Why Entity Framework Core?

· Developer Productivity.

· Consistent query syntax with LINQ to Entities.

· Supporting Non-Relational Databases.

Approaches to Model Entities in Entity Framework Core

● Code First — The Code First approach helps you to create the entities in your application by focusing on the domain requirements.

● Model First — In the Model First approach you can create the EDM first, then generate the database from it. You would typically create an empty EDM using the Entity Data Model Wizard in Visual Studio, define the entities and their relationships in Visual Studio, then generate the database from this defined model. (Removed in entity framework core)

● Database First — You can use the Database First approach if the database is already designed and is ready. In this approach, the Entity Data Model (EDM) is created from the underlying database.

Demo

dotnet ef must be installed as a global or local tool. Most developers will install dotnet ef as a global tool with the following command in the CMD: dotnet tool install --global dotnet-ef

Image for post
Image for post

To check that you have correctly installed dotnet ef use the following command in the CMD: dotnet-ef

Image for post
Image for post

In the above picture, you can see 3 commands there. I will explain one by one where we can use those commands. We can use the database command to sync or update the database. dbcontext command is not widely used but you can change the DbContext types using the dbcontext command. The database and migrations are commonly used commands. I guess you can better understand if I show you a demo.

Steps to add Entity Framework Core

1. Add Entity Framework Core Packages

a. Microsoft.EntityFrameworkCore

b. Microsoft.EntityFrameworkCore.Design — for migrations

c. Microsoft.EntityFrameworkCore.SqlServer — for SQL Server

2. Add Connection String

3. Create data context class

4. Add data context as a service and specify the data provider (sql/sqlite/cosmos)

As I mentioned earlier you have to add those 3 packages to your project. You can add these packages using the following commands :

1. dotnet add package Microsoft.EntityFrameworkCore

2. dotnet add package Microsoft.EntityFrameworkCore.Design

3. dotnet add package Microsoft.EntityFrameworkCore.SqlServer

After you successfully execute these commands you can see the references in your .csproj file. SQL Server database is the one I’m using for the database. That’s why I have used the dotnet add package Microsoft.EntityFrameworkCore.SqlServer command. Depends on the database you connect the code would differ.

Image for post
Image for post

Next, we have to create a data context class. It helps to maintain the session between the application and the database.

Image for post
Image for post

We just named it a context class but that doesn’t mean it’s a context class. Then how can our application know it’s a context class? This is why the entity framework core gives us a base class called DbContext. Then you have to include the namespace as I used in the line number 2 or else if you press ctrl + . in the VS code it will give you some suggestions. You can select it from there too. Hover the mouse pointer to the DbContext and press F12. You can see the DbContext metadata and methods that you can implement.

From this, you can find two DbContext constructors. In the first one, it uses DbContextOptions as a parameter. Thorough the DbContextOptions we are going to specify what data provider we are using, connection string we are using, etc.

public RolexBakeMartDbContext([NotNullAttribute] DbContextOptions options) : base(options)

{

}

Another method I will use here is OnModelCreating. We will use this when we are using the Fluent API. If we have any change in the entity or have to specify the keys, the relationship we can use this. I will explain further about Fluent API later.

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

base.OnModelCreating(modelBuilder);

}

Now we have to specify the connection string. Usually, we specify the connection string in the appsettings.json

“ConnectionStrings”: {

“DefaultConnection”: “Server=localhost; Database=RolexBakeMart; Trusted_Connection=True; MultipleActiveResultSets=true”

},

After doing this appsettings.json will looks like the following:

Image for post
Image for post

Then we have to go to the Startup.cs, this is where we add dependency injection, contracts. So, now we have to add DbContext class here. To add it here we need connection string. That’s what we did previously. Now we are going to tell our application that we are going to add Dbcontext class as a service and going to pass the connection string to it.

string connectionString = Configuration.GetConnectionString(“DefaultConnection”);

services.AddDbContext<RolexBakeMartDbContext>(opt => opt.UseSqlServer(connectionString));

Configuration is the interface that’s going to retrieve the configurations in appsettings.json and the name passed to it was the name I gave in the appsettings. You can refer to the above codes in appsettings. In the next line, I’m adding DbContext class to the services. Don’t forget to call the namespace where DbContext class belongs and also SqlServer provider.

Image for post
Image for post

Now we need a table based on the class we have here right. In that table, we need to specify the columns and primary key. Let’s see how we can define them. We can define them using the following two ways.

  1. Data Annotations

Data Annotations attributes are .NET attributes that can be applied to an entity class or properties to override default conventions in EF 6 and EF Core.

Data annotation attributes are included in the System.ComponentModel.DataAnnotations and System.ComponentModel.DataAnnotations.Schema namespaces in EF 6 as well as in EF Core. These attributes are not only used in Entity Framework but they can also be used with ASP.NET MVC or data controls

Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

Here we mentioned that when creating a table in the database, set the CategoryId as PrimaryKey.

We can do the same thing with another thing. Remember I have talked about Fluent API before.

2. Fluent API

Fluent API is used to configure domain classes to override conventions. EF Fluent API is based on a Fluent API design pattern where the result is formulated by method chaining. To write Fluent API configurations, We need to override the OnModelCreating() method of DbContext in a context class.

Fluent API configures the following aspect of a model in Entity Framework

Model-wide Configuration: Configures the default Schema, entities to be excluded in mapping, etc.

Entity Configuration: Configures entity to table and relationship mappings e.g. PrimaryKey, Index, table name, one-to-one, one-to-many, many-to-many, etc.

Property Configuration: Configures property to column mappings e.g. column name, nullability, Foreignkey, data type, concurrency column, etc.

Image for post
Image for post
Image for post
Image for post

We won’t use the Fluent API in the class. We will use it in the OnModelCreating() in the DbContext class. Before creating this we need to do one more thing. In the application Category is a class. To use this as a table in our database, we have to introduce this as a DbSet in DbContext class. DbSet is a collection of rows. Each row will represent the Category class in the database. Imagine Dbset as a Category table.

public DbSet<Category> Categories { get; set;}

When giving the dataset name you have to give the name in the plural.

Now let’s define the key attribute using the Fluent API.

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

base.OnModelCreating(modelBuilder);

modelBuilder.Entity<Category>().HasKey(x => x.CategoryId);

}

To create the table in the database we will use migrations.

Migrations

The migrations feature in EF Core provides a way to incrementally update the database schema to keep it in sync with the application’s data model while preserving existing data in the database.

Commands

● dotnet-ef migrations add Migration Name — add a new migration

● dotnet-ef migrations remove — remove the last migration

● dotnet-ef database update — update the database to the latest migration

● dotnet-ef migrations script — generate the sql script for the migration

Now let’s use migration in entity framework core to sync with the database. then only the model we created in the application will be created as a table in the database. first, you have to use the following command to add a new migration. Command: dotnet-ef migrations add “Category entity added”

Now you can see the change in the folder structure. There will be a new filed called Migrations. Now we have created Migrations but still, we didn’t apply it. Then only database will be created in the SqlServer. Now let’s see how we can apply this using the following command: dotnet-ef database update –verbose

Verbose will show what’s happening behind when we are applying this. Now all the data in the migrations will be synced with the database. Now you can check for the table in the database.

Image for post
Image for post

By default when we are executing the migration, it will look for the database. If it doesn’t exist, it will create it automatically. I hope you guys can get a clear understanding of Entity Framework Core now. If you get any errors while doing this you can refer my codes for your understanding. I have uploaded it to the GitHub. Use the following link to access it.

Thank You.

Written by

I’m a tech savvy person who loves to keep myself updated to the current trends of the technology world.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store