Skip to content

Latest commit

 

History

History
61 lines (43 loc) · 1.14 KB

File metadata and controls

61 lines (43 loc) · 1.14 KB

EntityFramework

Prerequisite installation

dotnet tool install --global dotnet-ef
dotnet add package Microsoft.EntityFrameworkCore.Design

Add DBContext class

Add class like below to project.

public class DataContext : DbContext
{
    public DataContext(DbContextOptions options) : base(options)
    {

    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite(@"Data Source=DBName.db");
    }

    // list Dbset Below to use
}

Add EF service to App

Add ef service to Program.cs:

builder.Services.AddDbContext<DataContext>();
//(Option way)
builder.Services.AddSqlite<DataContext>(builder.Configuration.GetConnectionString("DefaultConnection"));

Execute Ef command to create migrations

dotnet ef migrations add InitialCreate
dotnet ef database update

Seeding data

Seeding can be set in OnConfiguring method of the DbContext subclass:

optionsBuilder.UseSeeding((context, _) =>
    // use context to prepare data
);

After executing dotnet ef database update, UseSeeding method will be triggered.