Entity Framework Concepts
This section provides conceptual overviews and explanations of core Entity Framework features, helping you understand how to interact with your data in .NET applications.
What is Entity Framework?
Entity Framework (EF) is an object-relational mapper (ORM) that enables developers to work with relational data using domain-specific objects that are, in effect, custom-ordered variables. It eliminates the need for most of the data-access code that developers traditionally need to write. EF Core is the latest version of Entity Framework. It is a lightweight, extensible, and cross-platform version of Entity Framework. It is also the recommended version of Entity Framework to use for new applications.
Key Concepts
- Models: Define your data structure using C# classes. EF maps these classes to database tables.
- DbContext: The primary class that represents a session with the database and allows you to query and save data.
- DbSet: Represents a collection of entities of a particular type in the
DbContext. - Migrations: A powerful feature for managing database schema changes over time as your application evolves.
- LINQ to Entities: A query language that allows you to write queries against your entity models using Language Integrated Query (LINQ).
Getting Started with EF Core
Learn how to set up your project, define your models, and interact with your database for the first time.
View Tutorial: Getting Started with EF Core
Data Access Patterns
Explore common patterns for querying, adding, updating, and deleting data using Entity Framework.
Querying Data
Entity Framework provides powerful ways to retrieve data from your database using LINQ. You can filter, sort, and project your results into custom shapes.
// Example of querying users older than 30
var olderUsers = context.Users
.Where(u => u.Age > 30)
.OrderBy(u => u.LastName)
.ToList();
Saving Data
Adding, modifying, and removing entities is straightforward with the DbContext.
// Example of adding a new user
var newUser = new User { FirstName = "Jane", LastName = "Doe", Age = 25 };
context.Users.Add(newUser);
context.SaveChanges();
// Example of updating a user
var userToUpdate = context.Users.Find(userId);
if (userToUpdate != null)
{
userToUpdate.Age = 26;
context.SaveChanges();
}
// Example of deleting a user
var userToDelete = context.Users.Find(userId);
if (userToDelete != null)
{
context.Users.Remove(userToDelete);
context.SaveChanges();
}
Advanced Topics
Dive deeper into more complex scenarios like performance tuning, concurrency control, and working with relationships.