Getting Started with Entity Framework Core

This guide will walk you through the essential steps to start using Entity Framework Core (EF Core) in your .NET applications.

What is Entity Framework Core?

Entity Framework Core is a modern, cross-platform, open-source Object-Relational Mapper (ORM) for .NET. It enables .NET developers to work with databases using .NET objects, eliminating the need for most of the data-access code they typically need to write.

EF Core supports a variety of database providers, including:

Installation

You can install EF Core using the .NET CLI or the NuGet Package Manager in Visual Studio.

Using the .NET CLI

To install the core EF Core libraries and a database provider (e.g., SQL Server), run the following commands in your project directory:

dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Replace Microsoft.EntityFrameworkCore.SqlServer with the appropriate package for your database (e.g., Microsoft.EntityFrameworkCore.Npgsql for PostgreSQL).

Using Visual Studio NuGet Package Manager

  1. Right-click on your project in Solution Explorer and select "Manage NuGet Packages...".
  2. Go to the "Browse" tab.
  3. Search for Microsoft.EntityFrameworkCore and install it.
  4. Search for your specific database provider package (e.g., Microsoft.EntityFrameworkCore.SqlServer) and install it.

Creating a Model

EF Core uses Plain Old CLR Objects (POCOs) to represent your data. Define classes that reflect the structure of your database tables.

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public virtual ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public virtual Blog Blog { get; set; }
}

Creating a DbContext

The DbContext class represents a session with the database and allows you to query and save data. It's the entry point for interacting with your data.

using Microsoft.EntityFrameworkCore;

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    public BloggingContext(DbContextOptions<BloggingContext> options)
        : base(options)
    { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Optional: Configure relationships and constraints here
        modelBuilder.Entity<Blog>()
            .Property(b => b.Url)
            .IsRequired();
    }
}

Configuring the Database Connection

You need to tell EF Core which database to connect to. This is typically done in your application's startup configuration (e.g., Program.cs or Startup.cs).

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<BloggingContext>(options =>
    options.UseSqlServer(connectionString));

var app = builder.Build();

// ... rest of your application setup

Ensure you have a connection string defined in your appsettings.json file:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=BloggingEFCore;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

Important Note:

This connection string is for demonstration purposes. For production, use secure methods to manage your connection strings.

Using the DbContext

You can now inject your DbContext into your application's services or controllers to interact with the database.

Creating a New Blog

public class BlogsService
{
    private readonly BloggingContext _context;

    public BlogsService(BloggingContext context)
    {
        _context = context;
    }

    public void AddNewBlog(string url)
    {
        var blog = new Blog { Url = url };
        _context.Blogs.Add(blog);
        _context.SaveChanges(); // Saves changes to the database
    }
}

Querying Blogs

public IEnumerable<Blog> GetAllBlogs()
{
    return _context.Blogs.ToList(); // Fetches all blogs from the database
}

public Blog GetBlogByUrl(string url)
{
    return _context.Blogs.FirstOrDefault(b => b.Url == url);
}

Next Steps:

Now that you have the basics, explore how to model your data more deeply, perform complex queries, and manage database schema changes with migrations.