Setting up your environment for EF Core involves installing the necessary tools, configuring your .NET project, and preparing your database. This tutorial will guide you through the steps required to get started with EF Core.
Before you begin, ensure you have the following installed on your system:
Start by creating a new .NET project. You can use the command line or your preferred IDE.
dotnet new console -n EFCoreDemo
This command creates a new console application named EFCoreDemo.
Install EF Core packages using the .NET CLI or the NuGet Package Manager in Visual Studio. The essential packages are:
Use the following commands to install these packages:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Configure the DbContext in your project to manage database connections and entity mappings.
public class ApplicationDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("YourConnectionStringHere");
}
}
Specify the database connection string in your project. This can be done in the appsettings.json file or directly in your DbContext configuration.
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=EFCoreDemo;Trusted_Connection=True;"
}
}
Update your DbContext to use the connection string:
public class ApplicationDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
}
}
Use EF Core migrations to create and update your database schema. Begin by creating an initial migration:
dotnet ef migrations add InitialCreate
Then apply the migration to update your database:
dotnet ef database update
By following these steps, you have set up your environment to use EF Core with a .NET project. You can now define your entities, create migrations, and interact with your database using EF Core.