从TableAttribute Dapper.Contrib获取表名

时间:2017-03-26 18:23:23

标签: data-annotations dapper typeof

我正在使用Dapper和Dapper.Contrib来映射数据库中的对象。

我有一个类名,我为这个类定义了表名,因为它与实际的类名不同。

类别:

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

如何获取设置表数据注释属性的表名

修改

我已经使用了以下功能

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

tableName = tAttribute.Name;

2 个答案:

答案 0 :(得分:2)

我在控制台应用程序.NET Framework 4.6.2中对此进行了测试。如果您想了解有关该扩展程序的更多信息,请参阅SqlMappperExtensions

$ pgrep bash | xargs echo
5514 22298 23079

答案 1 :(得分:1)

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;
}

用法:

string postTableName = TableName<Post>();

或者您可以打开原始SqlMapperExtensions.GetTableName(Type type)方法并复制其代码。