从 TableAttribute Dapper.Contrib 获取表名

Has*_*anG 4 typeof data-annotations dapper

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

我有一个类名,我在其中定义该类的表名,因为它与实际的类名不同。

班级:

[Table("tblUser")]
public class User
{
    public int Id { get; set; }
    public string Title { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

编辑:

我用以下方法让它工作

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

tableName = tAttribute.Name;
Run Code Online (Sandbox Code Playgroud)

Wil*_*ras 5

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

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; }
    }
}
Run Code Online (Sandbox Code Playgroud)