-
Notifications
You must be signed in to change notification settings - Fork 0
Data Entity
Arsenty Politov edited this page Mar 15, 2019
·
1 revision
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.
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));
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" });
}
}