This library provides the engagement between Entity Framework Core and PosgreSQL. In other hand, it gives some services for CRUD such as IUnitOfWork, IRepository,.. Just do a litte code and let's start
This library requires .NET Core 3.x
$ Install-Package EFPostgresEngagement
$ dotnet add package EFPostgresEngagement
- Create a new environment variable for the Postgres connection
CONNECTION_STRING: '....'
- Create an entity base and let's in inherits DefaultEntityBase
public class EntityBase : DefaultEntityBase
{
}
- Create a new DbContext and let's it inherits PostgresDbContextBase
public class MyDataDbContext : PostgresDbContextBase<MyDataDbContext>
{
public MyDataDbContext(DbContextOptions<MyDataDbContext> options, IDbTracker dbTracker) : base(options,
dbTracker)
{
}
}
- Create a DbContext factory for migration --optional
public class MyDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
{
public MyDbContext CreateDbContext(string[] args)
{
var connection = Environment.GetEnvironmentVariable("CONNECTION_STRING");
var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseNpgsql(connection ?? <connection-string>");
return new MyDbContext(optionsBuilder.Options, null);
}
}
- Create class Repository and let's it inherits RepostoryBase
public class Repository<TEntity> : RepositoryBase<TEntity, MyDataDbContext>
where TEntity : class, new()
{
public Repository(MyDataDbContext dbContext) : base(dbContext)
{
}
}
- Create class UnitOfWork and let's it inherits UnitOfWorkBase
public class UnitOfWork : UnitOfWorkBase<MyDataDbContext>
{
public UnitOfWork(MyDataDbContext dbContext) : base(dbContext)
{
}
public override IRepository<T> GetRepository<T>()
{
return new Repository<T>(this.DbContext);
}
}
- Finally, registering all services in StartUp file
services
.UsePostgresSql<MyDataDbContext>(this.Configuration)
.AddTransient<IUnitOfWork, UnitOfWork>();
services.AddScoped<IDbTracker>(provider => new ApplicationUserProvider());
- Ok, just inject IUnitOfWork wherever you want to interact with database.
Note: IDbTracker helps to track the owner of data modification. In the near future, it will be optional. Temporarily for now, please implement a class to pass this requirement