gpt4 book ai didi

data-annotations - 从 TableAttribute Dapper.Contrib 获取表名

转载 作者:行者123 更新时间:2023-12-05 08:56:01 25 4
gpt4 key购买 nike

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

最佳答案

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

关于data-annotations - 从 TableAttribute Dapper.Contrib 获取表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43032797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com