Implementing abstraction of repositories using EntityFramework Core for access to data store.
Registration and configuration of entities context can occur from the RegisterContext<TDbContext>(dbContextOptionsBuilder => {}, entitiesBuilder => {})
method.
For use you needed install packages:
Install-Package Skidbladnir.Repository.EntityFrameworkCore
Sample entity:
public class SimpleMessage : IHasId<int>
{
public int Id { get; set; }
public string Text { get; set; }
public DateTime? Timestamp { get; set; }
}
Sample entity map:
public class SimpleMessageConfiguration : IEntityTypeConfiguration<SimpleMessage>
{
public void Configure(EntityTypeBuilder<SimpleMessage> builder)
{
builder.ToTable("MessageStore");
}
}
Sample DbContext (implements DbContextBase
):
public class SampleDbContext : DbContextBase
{
public SampleDbContext(DbContextOptions<SampleDbContext> options) : base(options)
{
}
public DbSet<SimpleMessage> Messages { get; set; }
public DbSet<SimpleGuid> Guids { get; set; }
}
Next, we register our DbContext, entity and its configuration. We use sqlite as a database.
Register theirs in ConfigureServices
method:
public void ConfigureServices(IServiceCollection services)
{
services.RegisterContext<SampleDbContext>(
builder => builder.UseSqlite("Data Source=sample.db;Cache=Shared"),
entities =>
{
entities.AddEntity<SimpleMessage, SimpleMessageConfiguration>();
}
);
}