Getting Started with Entity Framework Core on Plesk Print

  • 0

What is Entity Framework Core?

Entity Framework Core (EF Core) is a modern object-relational mapper (ORM) for .NET. It enables developers to work with databases using .NET objects, eliminating most data-access code.

Installing EF Core

Add the SQL Server package to your project:

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

Creating Your DbContext

using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options) { }

    public DbSet<Product> Products { get; set; }
    public DbSet<Category> Categories { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Product> Products { get; set; }
}

Configuring in Program.cs

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

Connection String in appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=MyAppDb;User Id=myuser;Password=mypassword;TrustServerCertificate=True;"
  }
}

Basic CRUD Operations

public class ProductService
{
    private readonly AppDbContext _context;

    public ProductService(AppDbContext context)
    {
        _context = context;
    }

    // Create
    public async Task<Product> CreateAsync(Product product)
    {
        _context.Products.Add(product);
        await _context.SaveChangesAsync();
        return product;
    }

    // Read
    public async Task<List<Product>> GetAllAsync()
    {
        return await _context.Products
            .Include(p => p.Category)
            .ToListAsync();
    }

    // Update
    public async Task UpdateAsync(Product product)
    {
        _context.Products.Update(product);
        await _context.SaveChangesAsync();
    }

    // Delete
    public async Task DeleteAsync(int id)
    {
        var product = await _context.Products.FindAsync(id);
        if (product != null)
        {
            _context.Products.Remove(product);
            await _context.SaveChangesAsync();
        }
    }
}

Querying with LINQ

// Filter
var expensiveProducts = await _context.Products
    .Where(p => p.Price > 100)
    .ToListAsync();

// Sort
var sortedProducts = await _context.Products
    .OrderByDescending(p => p.Price)
    .ToListAsync();

// Pagination
var pagedProducts = await _context.Products
    .Skip(20)
    .Take(10)
    .ToListAsync();

Best Practices

  • Use async methods (SaveChangesAsync, ToListAsync)
  • Use Include() for eager loading related data
  • Dispose DbContext properly (DI handles this)
  • Use migrations for database schema changes

See our "Entity Framework Core Migrations" article for database deployment.


Was this answer helpful?

« Back