Setting up Entity Framework Core

Setting up Entity Framework Core involves installing necessary packages, configuring the DbContext, and setting up your model classes.

Key Topics

Install Packages

Example

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

Explanation: These commands install the EF Core provider for SQL Server and the EF Core tools for running migrations.

Setup DbContext

Example

using Microsoft.EntityFrameworkCore;

public class MyDbContext : DbContext
{
    public DbSet Employees { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=localhost;Database=MyDatabase;User Id=myUser;Password=myPassword;");
    }
}

Explanation: The DbContext class is configured to use SQL Server with a connection string.

Create Model Classes

Example

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
}

Explanation: This example defines a simple Employee model class mapped to a database table.

Key Takeaways

  • Install the required EF Core NuGet packages for your project.
  • Configure the DbContext to manage database connections and model mappings.
  • Define model classes that represent database tables.