问题
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;
回答1:
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; }
}
}
回答2:
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.
来源:https://stackoverflow.com/questions/43032797/get-table-name-from-tableattribute-dapper-contrib