Introduction to ASP.NET Core and Entity Framework Core

Welcome to this foundational tutorial on using ASP.NET Core with Entity Framework Core (EF Core). This guide will walk you through the essential steps of setting up an ASP.NET Core application and integrating EF Core for data access. We'll cover creating a simple data model, setting up a database context, and performing basic CRUD (Create, Read, Update, Delete) operations.

Prerequisites

1. Setting Up the ASP.NET Core Project

Let's start by creating a new ASP.NET Core Web Application project. Open your terminal or command prompt and run the following command:

dotnet new webapp -o MyWebAppWithEFCore
cd MyWebAppWithEFCore

This command creates a new web application project named MyWebAppWithEFCore and navigates into its directory.

2. Adding EF Core Packages

Next, we need to add the necessary EF Core packages. We'll use the SQL Server provider for this example, but EF Core supports many other database providers.

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

The Microsoft.EntityFrameworkCore.Tools package is essential for using EF Core migration commands.

3. Defining the Data Model

Let's create a simple model for a Product.

Create a new folder named Models in your project's root directory and add a new C# file named Product.cs:

namespace MyWebAppWithEFCore.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public decimal Price { get; set; }
        public int Stock { get; set; }
    }
}

4. Creating the Database Context

The DbContext class is the main gateway to interact with your database. Create a new folder named Data and add a C# file named ApplicationDbContext.cs:

using Microsoft.EntityFrameworkCore;
using MyWebAppWithEFCore.Models;

namespace MyWebAppWithEFCore.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

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

5. Configuring the Database Connection

Open the appsettings.json file and add a connection string for your database. For SQL Server, it might look like this:

{
  "Logging": { ... },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyWebAppDB;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

You can replace (localdb)\mssqllocaldb and MyWebAppDB with your preferred SQL Server instance and database name.

Next, configure the DbContext in your Program.cs file:

using Microsoft.EntityFrameworkCore;
using MyWebAppWithEFCore.Data;

var builder = WebApplication.CreateBuilder(args);

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

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

var app = builder.Build();

// ... rest of your Program.cs

6. Creating Migrations

EF Core Migrations allow you to evolve your database schema over time. Let's create the initial migration:

dotnet ef migrations add InitialCreate
dotnet ef database update

This will create the necessary migration files and apply them to your database, creating the Products table.

7. Performing CRUD Operations

Now you can inject your ApplicationDbContext into your Razor Pages or Controllers to interact with the database.

Example: Adding a New Product (in a Razor Page's OnPostAsync method)

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using MyWebAppWithEFCore.Models;
using MyWebAppWithEFCore.Data;

namespace MyWebAppWithEFCore.Pages
{
    public class CreateProductModel : PageModel
    {
        private readonly ApplicationDbContext _context;

        public CreateProductModel(ApplicationDbContext context)
        {
            _context = context;
        }

        [BindProperty]
        public Product Product { get; set; } = new Product();

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            _context.Products.Add(Product);
            await _context.SaveChangesAsync();

            return RedirectToPage("./Index"); // Redirect to a page that lists products
        }
    }
}

You would similarly implement methods for reading, updating, and deleting products using _context.Products.ToListAsync(), _context.Products.Update(), and _context.Products.Remove() respectively, followed by await _context.SaveChangesAsync();.

Conclusion

This tutorial provided a basic introduction to integrating ASP.NET Core with Entity Framework Core. You've learned how to set up a project, add packages, define models, configure the context, create migrations, and perform fundamental data operations. Explore the official EF Core documentation for more advanced features like relationships, complex queries, and performance optimizations.

Next Steps: