【问题标题】:Get table name from TableAttribute Dapper.Contrib从 TableAttribute Dapper.Contrib 获取表名
【发布时间】:2017-03-26 18:23:22
【问题描述】:

我正在使用 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;

【问题讨论】:

    标签: data-annotations dapper typeof


    【解决方案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)方法并复制它的代码。

    【讨论】:

    【解决方案2】:

    我在控制台应用程序 .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; }
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 2011-12-03
    相关资源
    最近更新 更多