Amit Joshi
Amit Joshi

Reputation: 16389

How to get table name from POCO with Dapper Extensions mappings?

I have a table with name MyTable in my database. A POCO class MyTablePoco is created for that table.

Following is Mapping code of Dapper Extensions:

class MyTableMapper : ClassMapper<MyTablePoco>
{
    public MyTableMapper()
    {
        Table("MyTable");
        AutoMap();
    }
}

Following is the code where I need table name from POCO class:

private string GetTableName<T>()
{
    return typeof(T).Name.Replace("Poco", "");
}

My convention for naming POCO classes is TableName + "Poco". Based on this convention, my hack of replacing "Poco" from class name works great as shown in above example.

But, I would like to get the table name from mapping configurations instead. I think this will be more reliable as it avoids any string handling and assumptions about naming POCOs.

How can I get table name from POCO class with Dapper Extensions mappings?

Upvotes: 0

Views: 1435

Answers (1)

Amit Joshi
Amit Joshi

Reputation: 16389

I was submitted a pull request on GitHub. This is now merged in master branch. Hopefully this is now available out of the box and no need to download and modify the toolkit source code (as explained below) anymore. Note that I have not verified this as I am not using Dapper Extensions since few years.


Dapper Extensions project is open source; everyone knows that. I downloaded it from GitHub and modified it to meet my needs.

This feature is already present internally in library.

I added the following function in DapperExtensions.DapperExtensions static class:

public static string GetTableName<TPoco>() where TPoco : class
{
    return new SqlGeneratorImpl(_configuration).GetTableName(GetMap<TPoco>());
}

Here, TPoco is your POCO class.

Further, to get mapped column name, I added following function:

public static string GetColumnName<TPoco>(string propertyName) where TPoco : class
{
    return new SqlGeneratorImpl(_configuration).GetColumnName(GetMap<TPoco>(), propertyName, false);
}

Here, TPoco is your POCO class and propertyName is name of property of POCO class. One can easily get property name in Framework 4.5 or above as:

nameof(myPocoInstance.MyProperty)

Upvotes: 1

Related Questions