The comprehensive guide to Entity Framework Core


Entity Framework Core (EF Core) is a lightweight, extensible, and open-source version of Microsoft’s Entity Framework data access technology. It simplifies database interaction by providing an Object-Relational Mapping (ORM) framework that allows developers to work with databases using .NET objects. This eliminates much of the boilerplate data access code that developers traditionally need to write.

Installation

To begin using EF Core, you need to install it as a NuGet package. Open your terminal and run the following command inside your project directory:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

This installs the SQL Server provider for EF Core, but other providers are available for different databases.

Creating a Model

A model in EF Core consists of a set of classes that describe the data structure you want to store in the database. Each class corresponds to a table in the database. Let’s create a simple Book model:

public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
}

Creating a DbContext

The DbContext is a crucial component that manages the database connection, configures the model, and facilitates database queries. Here’s an example of creating a DbContext for our Book model:

using Microsoft.EntityFrameworkCore;

public class BookContext : DbContext
{
    public DbSet<Book> Books { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
    }
}

In this example, we’ve defined a DbSet<Book> property to represent the Book table in the database and configured the connection string.

Now, let’s add the Main method to demonstrate how to use these components together:

using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        // Ensure the database is created
        using (var context = new BookContext())
        {
            context.Database.EnsureCreated();
        }

        // Adding a Book
        using (var context = new BookContext())
        {
            var book = new Book { Title = "1984", Author = "George Orwell" };
            context.Books.Add(book);
            context.SaveChanges();
        }

        // Querying Books
        using (var context = new BookContext())
        {
            var books = context.Books.Where(b => b.Author == "George Orwell").ToList();
            foreach (var book in books)
            {
                Console.WriteLine($"Title: {book.Title}, Author: {book.Author}");
            }
        }
    }
}

In the Main method, we first ensure that the database is created. Then, we demonstrate adding a book and querying books from the database.

Advanced Topics

Now that you have a solid understanding of the basics of Entity Framework Core, let’s explore advanced topics that will empower you to handle more complex scenarios and optimize your database interactions.

Handling Relationships:

Entity Framework Core allows you to model and define relationships between entities in your data model.

Example: Adding a Publisher Entity

Let’s expand our model to include a Publisher entity:

public class Publisher
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }

    // Define a foreign key relationship
    public int PublisherId { get; set; }
    public Publisher Publisher { get; set; }
}

Now, configure the relationship in the BookContext:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Book>()
        .HasOne(b => b.Publisher)
        .WithMany()
        .HasForeignKey(b => b.PublisherId);
}

This example shows a one-to-many relationship between Publisher and Book.

Migrations:

Migrations enable you to evolve your database schema over time as your application evolves. To create and apply migrations, use the following commands:

dotnet ef migrations add InitialCreate
dotnet ef database update

This example creates an initial migration named InitialCreate and applies it to the database.

Asynchronous Operations:

Asynchronous operations in Entity Framework Core can enhance the scalability of your application.

Example: Using SaveChangesAsync and ToListAsync

// Adding a Book asynchronously
using (var context = new BookContext())
{
    var book = new Book { Title = "The Catcher in the Rye", Author = "J.D. Salinger" };
    context.Books.Add(book);
    await context.SaveChangesAsync();
}

// Querying Books asynchronously
using (var context = new BookContext())
{
    var books = await context.Books.Where(b => b.Author == "J.D. Salinger").ToListAsync();
}

Logging:

Entity Framework Core provides logging capabilities to help you understand what queries are being executed and diagnose performance issues.

Example: Configuring Logging

public class BookContext : DbContext
{
    private static readonly ILoggerFactory MyLoggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); });

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseLoggerFactory(MyLoggerFactory);
        optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
   }
}

In this example, logging is configured to write to the console.

Conclusion

Congratulations! You’ve now explored advanced topics in Entity Framework Core, including handling relationships, using migrations, performing asynchronous operations, and configuring logging. These features empower you to build robust and efficient data access layers in your .NET applications.

Remember to refer to the official documentation for in-depth information and best practices. Feel free to experiment and apply these concepts to real-world scenarios.

Next Post Previous Post
No Comment
Add Comment
comment url