从TableAttribute Dapper.Contrib获取表名 [英] Get table name from TableAttribute Dapper.Contrib
本文介绍了从TableAttribute Dapper.Contrib获取表名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Dapper和Dapper.Contrib来映射数据库中的对象。
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?
编辑:
以下使其正常工作
var tAttribute =
(TableAttribute)typeof(T).GetCustomAttributes(typeof(TableAttribute), true)[0];
tableName = tAttribute.Name;
推荐答案
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)方法并复制其代码。
Or you can open the original SqlMapperExtensions.GetTableName(Type type) method and copy its code.
这篇关于从TableAttribute Dapper.Contrib获取表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文