-
-
Notifications
You must be signed in to change notification settings - Fork 12
Repositories for SQL databases (Dapper)
Modern generic repositories for SQL databases are built on top of 2 most popular ORM frameworks: EF Core and Dapper.
To use Dapper repository install the Modern.Repositories.Dapper.DependencyInjection
Nuget package and register it within Modern builder in DI:
builder.Services
.AddModern()
.AddRepositoriesDapper(options =>
{
options.ProvideDatabaseConnection(() => new NpgsqlConnection(connectionString));
options.AddRepository<AirplaneDapperMapping, AirplaneDbo, long>();
});
Specify the type of Dapper mapping class, Dbo entity model and primary key.
A dapper needs to know how to create a database connection.
Since there are multiple database connection classes - provide the needed one using ProvideDatabaseConnection
method.
Dapper repository requires to have a small mapping class that way generic repository can match the entity property name with database table column.
ℹ️ Mapping class for Dapper is a part of Modern tools and not a part of Dapper library
For example consider the following mapping class:
public class AirplaneDapperMapping : DapperEntityMapping<AirplaneDbo>
{
protected override void CreateMapping()
{
Table("db_schema_name.airplanes")
.Id(nameof(AirplaneDbo.Id), "id")
.Column(nameof(AirplaneDbo.YearOfManufacture), "year_of_manufacture")
.Column(nameof(AirplaneDbo.ModelId), "model_id")
//...
;
}
}
Modern generic repositories are flexible, easily changeable and extendable. New methods can be added to repository as well as each method can be overriden.
The following interfaces can be inherited from:
IModernCrudRepository<TEntity, TId>
IModernQueryRepository<TEntity, TId>
Or inherit from a combined interface:
IModernRepository<TEntity, TId> : IModernCrudRepository<TEntity, TId>, IModernQueryRepository<TEntity, TId>
Lets have a look at example of inheritance from ModernDapperRepository:
public interface IAirplaneDapperRepository : IModernRepository<AirplaneDbo, long>
{
}
public class AirplaneDapperRepository : ModernDapperRepository<AirplaneDapperMapping, AirplaneDbo, long>, IAirplaneDapperRepository
{
public AirplaneDapperRepository(IDbConnectionFactory connectionFactory, AirplaneDapperMapping mapping, IQueryProviderFactory factory)
: base(connectionFactory, mapping, factory)
{
}
}