Skip to content

Data Entity

Arsenty Politov edited this page Mar 15, 2019 · 1 revision

DevGuild.AspNetCore.Services.Data.Entity

Contains implementation of IEntityStore and IRepository using EntityFrameworkCore. Additionally, contains IDbContextFactory service that can be used to construct a DbContext and DbSeed class that can be used for database seeding.

Adding services

To add services to dependency injection container, make following changes in Configure method of Startup class:

// Change optionsLifetime parameter of AddDbContext call to ServiceLifetime.Singleton.
// This way, DbContextOptions will be available as a singleton service.
services.AddDbContext<ApplicationDbContext>(
    options => options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")),
    optionsLifetime: ServiceLifetime.Singleton);

// Call AddEntityDataServices to register IRepository, IRepositoryFactory and IDbContextFactory
services.AddEntityDataServices<ApplicationDbContext>(
    options => new ApplicationDbContext(options));

Database seeding

To seed database from the service, create a class that inherits DbSeed<ApplicationDbContext> class, override its SeedAsync methods and call SeedEntityAsync extension of this.Context:

public class ApplicationDbSeed : DbSeed<ApplicationDbContext>
{
    public ApplicationDbSeed(IServiceProvider serviceProvider)
        : base(serviceProvider)
    {
    }

    public override async Task SeedAsync()
    {
        // Looks for entity with same primary key, if it do not exist - inserts the provided one.
        await this.Context.SeedEntityAsync(new Category { Id = 1, Name = "Default" });
    }
}
Clone this wiki locally