3

I'm using Dapper and Dapper.Contrib to map objects from database.

I have a class name where I define table name for this class because it is different from the actual class name.

Class:

[Table("tblUser")]
public class User
{
    public int Id { get; set; }
    public string Title { get; set; }
}

How can I get the table name which is set Table data annotation attribute?

EDIT:

I've used following to get it working

var tAttribute =
    (TableAttribute)typeof(T).GetCustomAttributes(typeof(TableAttribute), true)[0];

tableName = tAttribute.Name;
HasanG
  • 12,734
  • 29
  • 100
  • 154

2 Answers2

5

I tested this in a console application .NET Framework 4.6.2. Refer to the SqlMappperExtensions if you want more info on that extension.

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlMapperExtensions.TableNameMapper = TableNameMapper;
            var name = TableNameMapper(typeof(User));
        }

        private static string TableNameMapper(Type type)
        {
            dynamic tableattr = type.GetCustomAttributes(false).SingleOrDefault(attr => attr.GetType().Name == "TableAttribute");
            var name = string.Empty;

            if (tableattr != null)
            {
                name = tableattr.Name;
            }

            return name;
        }
    }

    [Table("tblUser")]
    public class User
    {
        public int Id { get; set; }
        public string Title { get; set; }
    }
}
William Xifaras
  • 5,212
  • 2
  • 19
  • 21
4
protected string TableName<T>()
{
    // Check if we've already set our custom table mapper to TableNameMapper.
    if (SqlMapperExtensions.TableNameMapper != null)
        return SqlMapperExtensions.TableNameMapper(typeof(T));

    // If not, we can use Dapper default method "SqlMapperExtensions.GetTableName(Type type)" which is unfortunately private, that's why we have to call it via reflection.
    string getTableName = "GetTableName";
    MethodInfo getTableNameMethod = typeof(SqlMapperExtensions).GetMethod(getTableName, BindingFlags.NonPublic | BindingFlags.Static);

    if (getTableNameMethod == null)
        throw new ArgumentOutOfRangeException($"Method '{getTableName}' is not found in '{nameof(SqlMapperExtensions)}' class.");

    return getTableNameMethod.Invoke(null, new object[] { typeof(T) }) as string;
}

Usage:

string postTableName = TableName<Post>();

Or you can open the original SqlMapperExtensions.GetTableName(Type type) method and copy its code.

Serg
  • 6,742
  • 4
  • 36
  • 54
  • How change attribute Table in runtime ? https://stackoverflow.com/questions/51269/change-attributes-parameter-at-runtime – Kiquenet Jul 02 '20 at 08:23
  • Not cannot set null to SqlMapperExtensions.TableNameMapper because use TypeTableName: https://github.com/StackExchange/Dapper/issues/1513 – Kiquenet Aug 07 '20 at 10:50