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

时间:2019-07-11 16:46:42

标签: c# reflection data-annotations

我想在运行时基于数据注释导出表名和列名。在我的代码示例中,我现在正在对值进行硬编码,但是我想以正确的方式进行操作。到处搜寻,但找不到解决方案。

[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);
                }

            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

有很多映射库都可以做到这一点,但是如果您确实需要通过反射来做到这一点,就可以这样做:

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
    }
  }
}