簡體   English   中英

根據數據注釋反映表/列名稱

[英]Reflect Table/Column names based on data annotation

我想在運行時基於數據注釋導出表名和列名。 在我的代碼示例中,我現在正在對值進行硬編碼,但是我想以正確的方式進行操作。 到處搜尋,但找不到解決方案。

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

            }
        }
    }
}

有很多可以執行此操作的映射庫,但是如果您確實需要通過反射來執行此操作,則可以執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM