首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >根据数据注释反映表/列名称

根据数据注释反映表/列名称
EN

Stack Overflow用户
提问于 2019-07-12 00:46:43
回答 1查看 109关注 0票数 0

我想在运行时根据数据注释派生表名和列名。在我的代码示例中,我暂时对值进行了硬编码,但我希望以正确的方式进行编码。我到处找,但找不到解决办法。

代码语言:javascript
运行
复制
[Table("T_MY_TBL")]
public class MyTable
{
    [Column("ID")]
    public int Id { get; set; }
    [Column("FNAME")]
    public string FirstName { get; set; }
}

public class MyLogic
{
    public void Save(List<MyTable> recs)
    {
        using (SqlConnection conn = new SqlConnection(connectionsTring))
        {
            conn.Open();
            using (SqlBulkCopy bc = new SqlBulkCopy(conn))
            {
                // want to reflect data-annotations instead of hard coding values
                using (var reader = FastMember.ObjectReader.Create(recs, "ID", "FNAME"))
                {
                    // want to reflect data-annotations instead of hard coding values
                    bc.DestinationTableName = "T_MY_TBL";
                    bc.WriteToServer(reader);
                }

            }
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2019-07-12 11:23:52

有很多映射库可以做到这一点,但是如果你真的需要用反射来做到这一点,你可以这样做:

代码语言:javascript
运行
复制
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
  foreach (Type type in assembly.GetTypes().Where(type => type.GetCustomAttribute<TableAttribute>() != null))
  {
    var tableAttribute = type.GetCustomAttribute<TableAttribute>();
    string tableName = tableAttribute.tableName; //whatever the field the of the tablename is

    foreach (var property in type.GetProperties().Where(property => property.GetCustomAttribute<ColumnAttribute>() != null))
    {
      var columnAttribute = property.GetCustomAttribute<ColumnAttribute>();
      var columnName = columnAttribute.columnName; //whatever the field the of the columnname is
    }
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56993920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档