Friday, 1 November 2024

How do you set up EF Core in a new ASP.NET Core project?

Setting up Entity Framework Core (EF Core) in a new ASP.NET Core project involves a few key steps, including adding the EF Core NuGet packages, configuring the DbContext, and setting up a database connection. Here’s a step-by-step guide:

1. Install EF Core Packages

Start by adding the EF Core packages to your ASP.NET Core project. Open the Package Manager Console and run the following commands based on the database provider you plan to use.

  • For SQL Server:


    dotnet add package Microsoft.EntityFrameworkCore.SqlServer
  • For SQLite:


    dotnet add package Microsoft.EntityFrameworkCore.Sqlite
  • For In-Memory (for testing):


    dotnet add package Microsoft.EntityFrameworkCore.InMemory
  • Additionally, you can add EF Core Tools to enable command-line migrations:


    dotnet add package Microsoft.EntityFrameworkCore.Tools

2. Create Your Model Classes

Define your entity classes that will represent tables in your database. For example, if you’re working with a Customer entity:


public class Customer { public int Id { get; set; } public string Name { get; set; } public string Email { get; set; } }

3. Create a DbContext Class

Create a class that derives from DbContext and includes DbSet properties for each entity. This DbContext class acts as a bridge between your application and the database.


public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Customer> Customers { get; set; } }

4. Configure the Database Connection String

In the appsettings.json file, add a connection string under "ConnectionStrings".

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

5. Register the DbContext in Dependency Injection

In the Startup.cs (ASP.NET Core 3.1 or earlier) or Program.cs (ASP.NET Core 5+), register the DbContext in the service container. Use the AddDbContext method, passing the database provider and connection string.


public void ConfigureServices(IServiceCollection services) { services.AddControllers(); // Register DbContext with SQL Server provider services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); }

6. Add and Run Migrations

To create the initial database schema based on your model classes, use EF Core migrations.

  • Add a Migration: Run the following command in the Package Manager Console or terminal to scaffold a migration.


    dotnet ef migrations add InitialCreate
  • Apply the Migration: Apply the migration to the database.


    dotnet ef database update

This will create the database and the necessary tables based on your model classes.

7. Inject and Use the DbContext in Controllers or Services

Now, inject the AppDbContext in your controllers or services to perform CRUD operations.


public class CustomersController : ControllerBase { private readonly AppDbContext _context; public CustomersController(AppDbContext context) { _context = context; } [HttpGet] public async Task<ActionResult<IEnumerable<Customer>>> GetCustomers() { return await _context.Customers.ToListAsync(); } }

8. Run the Application

Start your ASP.NET Core application, and the CustomersController will be able to interact with the Customers table in the database. You can access the API endpoints and perform CRUD operations to verify the EF Core setup.

Summary

This setup provides a quick way to configure EF Core in an ASP.NET Core application, allowing you to work with databases through DbContext and perform migrations, injections, and CRUD operations. This setup is also flexible and allows for adding more entities and configurations as needed.

Share:

0 comments:

Post a Comment