Dapperer 2.0.0

Dapperer an extension for Dapper

Install-Package Dapperer -Version 2.0.0
dotnet add package Dapperer --version 2.0.0
<PackageReference Include="Dapperer" Version="2.0.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Dapperer --version 2.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.

Dapperer is an extension for Dapper. It uses attributes on a database POCO entity classes to facilitate the followings.

  • A generic repository for basic CRUD operations on a relational database with no SQL query.
  • Populating sub-entities
  • Page-able queries
  • Cache-able query builder for the basic CURD operation queries.

Walk-through by example

Ref: [Dapperer.TestApiApp], please ignore the API best practices.

Database entities and Attributes

[Table("Contacts")]
public class Contact : IIdentifier<int>
{
    [Column("Id", IsPrimary = true, AutoIncrement = true)]
    public int Id { get; set; }

    [Column("Name")]
    public string Name { get; set; }

    public List<Address> Addresses { get; set; }

    public void SetIdentity(int identity)
    {
        Id = identity;
    }

    public int GetIdentity()
    {
        return Id;
    }
}

A database entity class must be extended from IIdentifier&lt;TPrimaryKey&gt;

  • Table attribute is to specify a table name
  • Column attribute is to specify column name and more such as
    • IsPrimary - Primary key or not
    • AutoIncrement if not auto increment then the key must be set before add/update an entity

Repositories

public class ContactRepository : Repository<Contact, int>
{
    public ContactRepository(IQueryBuilder queryBuilder, IDbFactory dbFactory)
        : base(queryBuilder, dbFactory)
    {
    }

    public virtual void PopulateAddresses(Contact contact)
    {
        PopulateOneToMany<Address, int>(address => address.ContactId, c => c.Addresses, contact);
    }

    public virtual Contact GetContactByName(string name)
    {
        ITableInfoBase tableInfo = GetTableInfo();
        string sql = string.Format(@"SELECT * FROM {0} WHERE Name = @Name", tableInfo.TableName);

        using (IDbConnection connection = CreateConnection())
        {
            return connection.Query<Contact>(sql, new { Name = name }).SingleOrDefault();
        }
    }
}

Dapperer conversion for a repository is one concrete repository per database entity. A concrete repository (ContactRepository in the above case) must be extended from the base Repository&lt;TEntity, TPrimaryKey&gt; which provides all the basic CRUD operations, page-able queries, etc. You can enjoy everything dapper provides in the extended repository class, GetContactByName is an example for writing your own custom queries.

What if you don't the basic CRUD functionality?

You can always use the core Dapper, using IDbFactory.

public class UserRepository : IUserRepository
{
    private readonly IDbFactory _dbFactory;

    public UserRepository(IDbFactory dbFactory)
    {
        _dbFactory = dbFactory;
    }

    public async Task<User> GetByEmailAsync(string email)
    {
        var sql = "SELECT * FROM Users WHERE email = @Email";

        using (var connection = _dbFactory.CreateConnection())
        {
            return (await connection.QueryAsync<User>(sql, new
            {
                Email = email
            }).SingleOrDefault();
        }
    }
}

Caching basic queries

In this current implementation of the Dapperer all the basic CRUD queries are cached in-memory. This needs a single instance of a single Query builder for the lifetime of your applications. This can be wired using dependency injection. In the test application used in this Walk-through uses Autofac, and its binding as follows.

builder.RegisterType<SqlQueryBuilder>().As<IQueryBuilder>().SingleInstance();

MS SQL Extras

Table-Valued Parameters are strongly typed user defined type that can be used in MS SQL database queries. IntList, LogList, StringList and GuidList are included part as helpers.

How to use them?

It's important to note that the custom types must exist in the database, check out the TVP sql here. For example,

CREATE TYPE IntList AS TABLE (
	Id INT NOT NULL PRIMARY KEY
);
public async Task<IList<User>> GetUsersAsync(IList<int> userIds)
{
    using (var connection = _dbFactory.CreateConnection())
    {
        const string sql = @"
            SELECT u.* 
            FROM @UserIds uid
            INNER JOIN Users u ON uid.Id = u.Id";

        return (await connection.QueryAsync<User>(sql, new
        {
            UserIds = new IntList(userIds).AsTableValuedParameter()
        })).ToList();
    }
}

Custom column mapping

It is important to note that if the if the column name in the database does not match the POCO entity class' property name then the POCO entity will not populate the right database value instead it'll be use default value of the property type.

Luckily Dapper solves that issues with custom column mappings, we leverage that to support our POCO entities with Table and Column attributes.

Registering Dapperer Mapping

For example, all the database entity class are in the same assembly as User database entity.

[Table("User")]
public class User : IIdentifier<int>
{
    [Column("UserId", IsPrimary = true, AutoIncrement = true)]
    public int Id { get; set; }

    [Column("User_Name")]
    public string Name { get; set; }

    public void SetIdentity(int identity) => Id = identity;

    public int GetIdentity() => Id;
}

Register column mappings - this should be done once, and can be done during the application initialization.

typeof(User).Assembly.UseDappererColumnMapping();

Configurations

Dapperer need a concrete implementation of IDappererSettings, take a look at DefaultDappererSettings in the example project.

<add key="Dapperer.ConnectionString" value="Server=localhost;Database=dapper_test;Trusted_Connection=True;" />

Databases

Dapperer can be extended for different databases other than SQL database you must create the following for any new databases

  • QueryBuilder for the database which extends IQueryBuilder
  • DbFactory for creating database connection which extends IDbFactory

Dapperer is an extension for Dapper. It uses attributes on a database POCO entity classes to facilitate the followings.

  • A generic repository for basic CRUD operations on a relational database with no SQL query.
  • Populating sub-entities
  • Page-able queries
  • Cache-able query builder for the basic CURD operation queries.

Walk-through by example

Ref: [Dapperer.TestApiApp], please ignore the API best practices.

Database entities and Attributes

[Table("Contacts")]
public class Contact : IIdentifier<int>
{
    [Column("Id", IsPrimary = true, AutoIncrement = true)]
    public int Id { get; set; }

    [Column("Name")]
    public string Name { get; set; }

    public List<Address> Addresses { get; set; }

    public void SetIdentity(int identity)
    {
        Id = identity;
    }

    public int GetIdentity()
    {
        return Id;
    }
}

A database entity class must be extended from IIdentifier&lt;TPrimaryKey&gt;

  • Table attribute is to specify a table name
  • Column attribute is to specify column name and more such as
    • IsPrimary - Primary key or not
    • AutoIncrement if not auto increment then the key must be set before add/update an entity

Repositories

public class ContactRepository : Repository<Contact, int>
{
    public ContactRepository(IQueryBuilder queryBuilder, IDbFactory dbFactory)
        : base(queryBuilder, dbFactory)
    {
    }

    public virtual void PopulateAddresses(Contact contact)
    {
        PopulateOneToMany<Address, int>(address => address.ContactId, c => c.Addresses, contact);
    }

    public virtual Contact GetContactByName(string name)
    {
        ITableInfoBase tableInfo = GetTableInfo();
        string sql = string.Format(@"SELECT * FROM {0} WHERE Name = @Name", tableInfo.TableName);

        using (IDbConnection connection = CreateConnection())
        {
            return connection.Query<Contact>(sql, new { Name = name }).SingleOrDefault();
        }
    }
}

Dapperer conversion for a repository is one concrete repository per database entity. A concrete repository (ContactRepository in the above case) must be extended from the base Repository&lt;TEntity, TPrimaryKey&gt; which provides all the basic CRUD operations, page-able queries, etc. You can enjoy everything dapper provides in the extended repository class, GetContactByName is an example for writing your own custom queries.

What if you don't the basic CRUD functionality?

You can always use the core Dapper, using IDbFactory.

public class UserRepository : IUserRepository
{
    private readonly IDbFactory _dbFactory;

    public UserRepository(IDbFactory dbFactory)
    {
        _dbFactory = dbFactory;
    }

    public async Task<User> GetByEmailAsync(string email)
    {
        var sql = "SELECT * FROM Users WHERE email = @Email";

        using (var connection = _dbFactory.CreateConnection())
        {
            return (await connection.QueryAsync<User>(sql, new
            {
                Email = email
            }).SingleOrDefault();
        }
    }
}

Caching basic queries

In this current implementation of the Dapperer all the basic CRUD queries are cached in-memory. This needs a single instance of a single Query builder for the lifetime of your applications. This can be wired using dependency injection. In the test application used in this Walk-through uses Autofac, and its binding as follows.

builder.RegisterType<SqlQueryBuilder>().As<IQueryBuilder>().SingleInstance();

MS SQL Extras

Table-Valued Parameters are strongly typed user defined type that can be used in MS SQL database queries. IntList, LogList, StringList and GuidList are included part as helpers.

How to use them?

It's important to note that the custom types must exist in the database, check out the TVP sql here. For example,

CREATE TYPE IntList AS TABLE (
	Id INT NOT NULL PRIMARY KEY
);
public async Task<IList<User>> GetUsersAsync(IList<int> userIds)
{
    using (var connection = _dbFactory.CreateConnection())
    {
        const string sql = @"
            SELECT u.* 
            FROM @UserIds uid
            INNER JOIN Users u ON uid.Id = u.Id";

        return (await connection.QueryAsync<User>(sql, new
        {
            UserIds = new IntList(userIds).AsTableValuedParameter()
        })).ToList();
    }
}

Custom column mapping

It is important to note that if the if the column name in the database does not match the POCO entity class' property name then the POCO entity will not populate the right database value instead it'll be use default value of the property type.

Luckily Dapper solves that issues with custom column mappings, we leverage that to support our POCO entities with Table and Column attributes.

Registering Dapperer Mapping

For example, all the database entity class are in the same assembly as User database entity.

[Table("User")]
public class User : IIdentifier<int>
{
    [Column("UserId", IsPrimary = true, AutoIncrement = true)]
    public int Id { get; set; }

    [Column("User_Name")]
    public string Name { get; set; }

    public void SetIdentity(int identity) => Id = identity;

    public int GetIdentity() => Id;
}

Register column mappings - this should be done once, and can be done during the application initialization.

typeof(User).Assembly.UseDappererColumnMapping();

Configurations

Dapperer need a concrete implementation of IDappererSettings, take a look at DefaultDappererSettings in the example project.

<add key="Dapperer.ConnectionString" value="Server=localhost;Database=dapper_test;Trusted_Connection=True;" />

Databases

Dapperer can be extended for different databases other than SQL database you must create the following for any new databases

  • QueryBuilder for the database which extends IQueryBuilder
  • DbFactory for creating database connection which extends IDbFactory

  • .NETFramework 4.5.1

  • .NETStandard 2.0

This package is not used by any popular GitHub repositories.

Version History

Version Downloads Last updated
2.0.0 1,023 10/26/2018
1.0.0.16-pre 639 7/27/2018
1.0.0.15 927 5/8/2015
1.0.0.13 535 4/1/2015
1.0.0.11 570 10/10/2014
1.0.0.10 523 9/16/2014