2017-06-05 35 views
0

我試圖建立一個通用的SQL執行器。如何在SqlDataReader上下文中使用屬性?

它的工作,如果我的DTO類屬性具有相同的名稱比我的SQL表列。

爲了增加我的代碼的泛型部分,我添加了一個屬性到我的DTO中,以便將我的DTO屬性分隔到SQL列。

但它不工作

我的DTO類:

public class CarModels 
{ 
    [DbColumn("ca_id")] //column name 
    public string Id { get; set; } 

    [DbColumn("ca_label")] //column name 
    public string Label { get; set; } 
} 

我的泛型方法:

public List<T> ExecuteSQLSELECTCommand<T>(string SQLcommand) where T : new() 
    { 
     IDictionary<string, string> databaseMappings = new Dictionary<string, string>(); ; 

     Get_Connection(); 
     using (MySqlCommand cmd = new MySqlCommand()) 
     { 

      cmd.Connection = connection; 
      cmd.CommandText = string.Format(SQLcommand); 
      List<T> res = new List<T>(); 
      try 
      { 
       MySqlDataReader reader = cmd.ExecuteReader(); 

       while (reader.Read()) 
        { 
        T t = new T(); 

        for (int inc = 0; inc < reader.FieldCount; inc++) 
        { 

          Type type = t.GetType(); 
         //how to get attribute link to current FiedCount ? 
          PropertyInfo prop = type.GetProperty(reader.GetName(inc)); 
          prop.SetValue(t, reader.GetValue(inc), null);     

        } 
        res.Add(t); 
       } 

       reader.Close(); 
      } 
      catch (Exception e) 
      { 

      } 
      return res; 
     } 
    } 

和我的電話:

List<CarModels> carTest = db.ExecuteSQLCommand<CarModels>("SELECT ca_id, ca_label from cartracker.ca_cars"); 

我的問題,怎麼能我恢復了att的價值ribute爲了在MySqlDataReader上下文中構建一個PropertyInfo?

謝謝。

回答

0

你可以使用這樣的一個類。你能告訴我,如果有幫助:

public class AnEntity<T> where T : class, new() 
{ 
    public T AnEntity(string[] token, ref int i, out TokenEnum tokenEnum, 
             out string tokenException) 
    { 
     ... 
     PropertyInfo[] properties = typeof(T).GetProperties(); 
     try 
     { 
      foreach (PropertyInfo property in properties) 
      { 
       ... 
        if (property.Name == "AName") 
        { 
         break; 
        } 
... 
相關問題