que-es-entity-framework

What is Entity Framework

  • 5 min

Entity Framework is an Object-Relational Mapping (ORM) developed by Microsoft as part of its .NET technology platform.

The main goal of Entity Framework (EF) is to simplify access to relational databases by abstracting the data access logic.

That is, instead of writing SQL queries “by hand,” with Entity Framework we can work with the database directly using C# code.

Entity Framework will handle all the heavy lifting in the database for us (like mapping between C# entities and tables, performing CRUD operations, etc.).

With Entity Framework, managing data in .NET applications becomes very simple and fast. It allows us to focus on business logic and be more productive (which will make your boss very happy 😏).

entity-framework

So we are going to dedicate this course to getting to know Entity Framework. But before diving deeper, let’s start at the beginning by seeing what an ORM is 👇.

What is an ORM?

A ORM is a technology that maps objects from a programming language to tables in a relational database.

In our case, Entity Framework is for C#. But there are many other ORMs for many other languages.

Instead of writing SQL queries, we can interact with the database using objects and methods provided by the ORM. This simplifies data access and reduces the amount of repetitive code.

That is, instead of using a raw SQL query like this,

SELECT * FROM Users WHERE Id = 1;
Copied!

With an ORM like Entity Framework, we can write:

var user = context.Users.Find(1);
Copied!

This not only makes the code more readable and maintainable but also reduces the probability of errors and speeds up development.

Code-First and Database-First Approaches

Entity Framework offers two distinct approaches for working with databases,

  • Code-First: You design the classes in C# and EF generates the database.
  • Database-First: It generates C# classes from an existing database.

As it could not be otherwise, each approach has its use, advantages, and disadvantages (If it were easy to choose, wouldn’t it?).

Having one approach or the other is a decision we have to make from the start, in every project where we use Entity Framework (we’ll see it in depth in due time).

Main Features of Entity Framework

Entity Framework has a series of features and functions that make it an extremely powerful tool when doing .NET projects. Let’s look at some of them.

Entity Framework Core uses LINQ (Language Integrated Query) as the primary language to interact with the database, allowing you to write strongly typed queries directly in C#.

var expensiveProducts = await _context.Products  
    .Where(p => p.Price > 100)  
    .OrderBy(p => p.Name)  
    .ToListAsync();  
Copied!

This not only is very convenient and improves code readability, but also prevents common errors like SQL syntax errors, since queries are validated at compile time.

For example, when filtering products with Where(p => p.Price > 100), EF Core translates this expression into an optimized SQL query like SELECT * FROM Products WHERE Price > 100.

One of the biggest advantages of EF Core is its ability to work with various database engines, from relational systems like SQL Server, PostgreSQL, and MySQL to embedded options like SQLite or NoSQL databases like Cosmos DB.

This is achieved through a system of database providers, which adapt EF Core operations to the specific SQL dialect of each engine.

For example, the same code that uses ToListAsync() in an application can run unchanged against SQL Server or PostgreSQL, simplifying portability between environments.

The change tracking mechanism of EF Core automatically tracks modifications in entities and generates optimized SQL commands when calling SaveChangesAsync().

var product = await _context.Products.FindAsync(1);  
product.Price = 150; // EF detects the change  
await _context.SaveChangesAsync(); // Generates "UPDATE Products SET Price = 150 WHERE Id = 1"  
Copied!

For example, if you modify a product’s price with product.Price = 150, EF Core detects this change and, when saving, executes only the necessary UPDATE, without requiring manual queries.

Migrations in EF Core are a versioned system for managing changes to the database schema without losing existing data.

dotnet ef migrations add “Inicial”
dotnet ef database update

When creating a migration, EF compares the current entity model with the previous one and generates incremental SQL scripts (like adding a column or creating a table). Then, it applies those changes to the database.

Advantages of Using Entity Framework

Obviously, the main advantage Entity Framework offers is development speed (and once again, your boss will be very happy and give you a promotion 💰).

But besides that, there are other advantages worth mentioning.

  • Productivity: Reduces the amount of repetitive code and simplifies data access.
  • Maintainability: The code is cleaner and easier to understand.
  • Security: Reduces the risk of errors or even security holes.
  • Portability: It’s much easier to switch from one database engine to another.

Throughout this course, we will see its features, advantages, and best practices so you can get the most out of it in your projects. Let’s get started! 🚀