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 data access logic.

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

Entity Framework will take care of doing all the heavy lifting in the database for us (such as mapping between C# entities and tables, performing CRUD operations, etc.).

With Entity Framework, handling 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 😏).

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

What is ORM?

An 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;

With an ORM like Entity Framework, we can write:

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

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

Code-First and Database-First Approaches

Entity Framework offers two distinct approaches to work with databases:

  • Code-First: You design the classes in C# and EF generates the database.
  • Database-First: 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, right?).

Choosing one approach or another is a decision we must make from the beginning in each project that uses Entity Framework (we will explore this in depth later).

Main Features of Entity Framework

Entity Framework offers a number of features that make it a powerful and essential tool in .NET application development:

Let’s look at some of these features.

Entity Framework Core uses LINQ (Language Integrated Query) as the main 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();  

This not only is very convenient and enhances code readability, but also prevents common errors such as SQL syntax errors, as 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 greatest 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 that adapt EF Core operations to the specific SQL dialect of each engine.

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

The change tracking mechanism of EF Core automatically tracks modifications to 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"  

For example, if you modify the price of a product 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 "Initial"  
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). It then applies those changes to the database.

Advantages of Using Entity Framework

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

But also, there are other advantages worth mentioning:

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