Working with Entity Framework Core

Entity Framework Core (EF Core) is a powerful Object-Relational Mapping (ORM) framework provided by Microsoft for .NET applications. It simplifies data access and persistence by allowing developers to work with databases using .NET objects, thus abstracting away the complexity of database interactions. In this article, we'll explore the fundamentals of Entity Framework Core, covering setup, basic operations, migrations, and advanced querying techniques.

Getting Started with Entity Framework Core

Before diving into EF Core, ensure you have the necessary tools installed.

Install EF Core: Include EF Core in your project using NuGet Package Manager or .NET CLI.

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Setup DbContext: Define a DbContext the class that represents your database context and includes DbSet properties for your entities.

public class MyDbContext : DbContext
{
    public DbSet<User> Users { get; set; }
    // Add more DbSet properties for other entities
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("YourConnectionString");
    }
}

Performing Basic Operations

Let's look at how to perform basic CRUD operations using EF Core.

Creating Records

To add new records to the database.

using (var context = new MyDbContext())
{
    var newUser = new User { FirstName = "John", LastName = "Doe", Email = "[email protected]" };
    context.Users.Add(newUser);
    context.SaveChanges();
}

Reading Records

To retrieve data.

using (var context = new MyDbContext())
{
    var newUser = new User { FirstName = "John", LastName = "Doe", Email = "[email protected]" };
    context.Users.Add(newUser);
    context.SaveChanges();
}

Updating Records

To update existing records.

using (var context = new MyDbContext())
{
    var userToUpdate = context.Users.FirstOrDefault(u => u.Id == 1);
    if (userToUpdate != null)
    {
        userToUpdate.Email = "[email protected]";
        context.SaveChanges();
    }
}

Deleting Records

To delete records.

using (var context = new MyDbContext())
{
    var userToUpdate = context.Users.FirstOrDefault(u => u.Id == 1);
    if (userToUpdate != null)
    {
        userToUpdate.Email = "[email protected]";
        context.SaveChanges();
    }
}

Using Migrations

Migrations in EF Core allow you to manage changes to your database schema over time. Here’s how to create and apply migrations.

Create Initial Migration: Generate an initial migration for your DbContext.

dotnet ef migrations add InitialCreate

Apply Migrations: Update the database with the generated migration.

dotnet ef database update

Advanced Querying with EF Core

EF Core supports LINQ (Language-Integrated Query) for powerful and expressive querying.

using (var context = new MyDbContext())
{
    var filteredUsers = context.Users
                             .Where(u => u.FirstName.StartsWith("J"))
                             .OrderBy(u => u.LastName)
                             .ToList();
}

Summary

Entity Framework Core simplifies data access in .NET applications by providing a rich set of tools for working with databases. From basic CRUD operations to advanced querying and database migrations, EF Core streamlines the development process, allowing developers to focus more on business logic and less on database plumbing. Start integrating EF Core into your projects today to leverage its benefits and accelerate your application development.

In this article, we've covered the essentials of working with Entity Framework Core, from setup and basic operations to migrations and advanced querying techniques. Whether you're building a new application or refactoring an existing one, EF Core's capabilities can significantly enhance your productivity and maintainability.


Similar Articles