2017-09-03 68 views
2

如何動態設置類的插入?如何循環使用列表中的每個列中的每個列<class>在c#中的每個列表使用

我該如何獲得每個在foreach循環中設置的類的列? 如何設置列表<>中的IEmployee或Custom類的每一列與foreach循環中的字符串[]值配對?

我想使用foreach循環動態地將自定義類插入到數據庫中。不用循環。

如果有動態插入自定義類,而無需使用for循環 方式下面是代碼:

public class Employee : IEmployee 
{ 
    private string _fname; 
    public string Firstname 
    { 
     get { return _fname; } 
     set { _fname = value; } 
    } 

    private string _lname; 
    public string Lastname 
    { 
     get { return _lname; } 
     set { _lname = value; } 
    } 

    private int _age; 

    public int Age 
    { 
     get { return _age; } 
     set { _age = value; } 
    } 

    private Gender _sex; 
    public Gender Sex 
    { 
     get { return _sex; } 
     set { _sex = value; } 
    } 

    private string _position; 
    public string Position 
    { 
     get { return _position; } 
     set { _position = value; } 
    } 

    private DateTime _bday; 
    public DateTime BirthDay 
    { 
     get { return _bday; } 
     set { _bday = value; } 
    } 
} 


string[] empcoltest = 
    { 
     "userid", 
     "fname", 
     "mname", 
     "lname", 
     "gender", 
     "position", 
     "birthday" 

    }; 




public void function(List<IEmployee> EmpList) 
{ 
    string[] columns, values; 
     columns = empcoltest; 
     values = new string[columns.Length]; 
     for (int a = 0; a < columns.Length; a++) 
     { 
      columns[a] = columns[a].Trim(); 
      values[a] = "@col" + a.ToString(); 
     } 
    string strEmp2 = @"INSERT INTO tblEmployees(" + string.Join(", ", columns) + ") VALUES(" + string.Join(", ", values) + ")"; 


    using (SqlCommand cmd = new SqlCommand(strEmp2, sqlDB.SqlDB)) 
    { 
    sqlDB.connect(); 


    foreach (string t in values) 
    { 
     foreach (IEmployee Emp in) 
     { 
      cmd.Parameters.AddWithValue(t,Emp); 
     } 
    } 

    } 

} 

我想做的事是這樣的

foreach (string t in values) 
{ 
    foreach (IEmployee Emp in) 
    { 
    //how do i set the Emp dynamically 
    cmd.Parameters.AddWithValue(t,Emp); 

    } 
    } 

回答

0

請嘗試要在發佈代碼時提供更多詳細信息,請不要一次性放置代碼。 你可以使用反射循環遍歷你的類,並設置值或獲取值或獲取屬性的名稱等等。 關於反射的教程https://www.youtube.com/watch?v=y8-uq6Ur7Dc的推薦。

我做了簡單的例子,在控制檯應用程序,只是爲了說明

這裏是Employee類

class Employee 
{ 
    public int FirstProp{ get; set; } 
    public string SecondProp { get; set; } 
} 

反射法

public static void EmployeeReflection(List<Employee> EmpList) 
    { 
     PropertyInfo[] pInfo = typeof(Employee).GetProperties(); 
     //or 
     // PropertyInfo[] pinfo = EmpList.GetType().GetProperties(); 
     for (int i= 0; i < EmpList.Count; i++) 
      { 
       string name = pInfo[i].Name; 
       object value = pInfo[i].GetValue(EmpList[i]); 
       Console.WriteLine("property name: " + name); 
       Console.WriteLine("property value: " + value); 
       Console.WriteLine(".........."); 

      } 

      /* or using foreach 
     int count = 0; 
     foreach (Employee emp in EmpList) 
     { 
      string name = pInfo[count].Name; 
      object value = pInfo[count].GetValue(emp); 
      Console.WriteLine("property name: " + name); 
      Console.WriteLine("property value: " + value); 
      Console.WriteLine(".........."); 
      count++; 
     } 
     */ 

    } 

並調用方法

 static void Main(string[] args) 
    { 

     List<Employee> listOfEmploies = new List<Employee> 
     { 
      new Employee { FirstProp = 1, SecondProp = "SomeText01" }, 
      new Employee { FirstProp = 2, SecondProp = "SomeText02" } 
     }; 
     EmployeeReflection(listOfEmploies); 

     Console.ReadLine(); 
    } 

您還需要using System.Reflection

*讓我分享我的課程,該課程創建了在我爲研究生作品製作應用時創建的選擇,插入,更新和刪除查詢。

調用的條件是您的類與SQL表具有相同的名稱,並且類中的屬性的索引與SQL表中的列相同。當調用這個類,構造takses SqlConnection的OBJ *

這裏是我的類

class SqlHelper<T> where T : new() 
{ 
    private PropertyInfo[] pInfo = typeof(T).GetProperties(); 
    private string sqlTable = typeof(T).Name; //i've made this filed becouse i've named my classes same as tables in SQL 
    public SqlConnection Con { get; set; } 
    private StringBuilder sb = new StringBuilder(); 
    private List<string> columns = new List<string>(); 
    public SqlHelper(SqlConnection con) 
    { 
     this.Con = con; 
    } 

    private void GetNames() 
    { 
     SqlCommand cmd = new SqlCommand("SELECT * FROM " + sqlTable, Con); 
     try 
     { 
      Con.Open(); 
      SqlDataReader dr = cmd.ExecuteReader(); 
      for (int i = 0; i < dr.FieldCount; i++) 
      { 
       if (!columns.Contains(dr.GetName(i))) 
        columns.Add(dr.GetName(i)); 
      } 
     } 
     catch (Exception) 
     { 
      return; 
     } 
     finally 
     { 
      Con.Close(); 
     } 
    } 
    public List<T> ReturnSelect() 
    { 
     List<T> listGen = new List<T>(); 
     SqlCommand cmd = new SqlCommand("SELECT * FROM " + sqlTable, Con); 
     try 
     { 
      Con.Open(); 
      SqlDataReader dr = cmd.ExecuteReader(); 
      while (dr.Read()) 
      { 
       T obj = new T(); 
       for (int i = 0; i < dr.FieldCount; i++) 
       { 
        if (!Convert.IsDBNull(dr[i])) 
         pInfo[i].SetValue(obj, dr.GetValue(i)); 

       } 
       listGen.Add(obj); 

      } 

      return listGen; 
     } 
     catch (Exception) 
     {   
      return null; 
     } 
     finally { Con.Close(); } 
    } 

    public bool InsertInto(T obj) 
    { 
     SqlCommand cmd = new SqlCommand(); 
     cmd.Connection = Con; 
     sb.Clear(); 
     sb.Append("INSERT INTO " + sqlTable + " VALUES("); 
     if (columns.Count == 0) 
      GetNames(); 
     string s1 = ","; 
     for (int i = 1; i < columns.Count; i++) 
     { 
      if (columns.Count - 1 == i) 
       s1 = ")"; 
      sb.Append("@" + pInfo[i].Name + s1); 
      cmd.Parameters.AddWithValue("@" + pInfo[i].Name, pInfo[i].GetValue(obj)); 

     } 

     cmd.CommandText = sb.ToString(); 

     try 
     { 
      Con.Open(); 
      cmd.ExecuteNonQuery(); 
      return true; 
     } 
     catch (Exception) 
     { 
      return false; 
     } 
     finally 
     { 
      Con.Close(); 
     } 
    } 
    public bool Update(T obj) 
    { 
     sb.Clear(); 
     SqlCommand cmd = new SqlCommand(); 
     cmd.Connection = Con; 
     sb.Append("UPDATE " + sqlTable + " SET "); 
     string s1 = ","; 
     if (columns.Count == 0) 
      GetNames(); 
     for (int i = 1; i < columns.Count; i++) 
     { 
      if (columns.Count - 1 == i) 
       s1 = ""; 
      sb.Append(columns[i] + "=" + "@" + pInfo[i].Name + s1); 

      cmd.Parameters.AddWithValue("@" + pInfo[i].Name, pInfo[i].GetValue(obj)); 
     } 
     sb.Append(" WHERE " + columns[0] + "=" + "@" + pInfo[0].Name + ";"); 
     cmd.Parameters.AddWithValue("@" + pInfo[0].Name, pInfo[0].GetValue(obj)); 

     cmd.CommandText = sb.ToString(); 

     try 
     { 
      Con.Open(); 
      cmd.ExecuteNonQuery(); 
      return true; 
     } 
     catch (Exception) 
     { 
      return false; 
     } 
     finally 
     { 
      Con.Close(); 
     } 

    } 
    public bool Delete(T obj) 
    { 
     if (columns.Count == 0) 
      GetNames(); 
     string id = $"@{pInfo[0].Name}"; 
     SqlCommand cmd = new SqlCommand("DELETE FROM " + sqlTable + " WHERE " + columns[0] + "=" + id, Con); 
     cmd.Parameters.AddWithValue(id, pInfo[0].GetValue(obj)); 
     try 
     { 
      Con.Open(); 
      cmd.ExecuteNonQuery(); 
      return true; 
     } 
     catch (Exception) 
     { 
      return false; 
     } 
     finally 
     { 
      Con.Close(); 
     } 

    } 
} 

例如,這是它如何工作的:

SqlHelper<Employee> hlp = new SqlHelper<Employee>(new SqlConnection 
      (new SqlConnectionStringBuilder 
      { 
       DataSource = @"(local)\SQLEXPRESS", 
       InitialCatalog = "SomeDatabase", 
       IntegratedSecurity = true 
      }.ToString())); 

     Employee e = new Employee { FirstProp = 3, SecondProp = "SomeText3" }; 
     List<Employee> list = hlp.ReturnSelect(); 
     bool Insertresult= hlp.InsertInto(e); 
     bool Updateresult=hlp.Update(e); 
     bool Deleteresult=hlp.Delete(e); 

希望這有助於。

相關問題