2016-07-29 10 views
1

大家好我想要在asp.net中使用mvc插入一些值到數據庫。我聽說在插入數據時它會是很好的使用對象。那麼如何通過在類中設計的屬性使用對象列表來實現這一點。如何使用對象和模式的列表(列表<Object>)將數據插入數據庫?

有稱爲類,

public class Customer 
    { 
     public string Name { get; set; } 
     public string Company { get; set; } 
     public int Telephone { get; set; } 
     public string Email { get; set; } 
     public int Id { get; set; } 
    } 

所以我有一個另一類只是做SQL命令

DBAccess.cs

public List<Customer> AddCustomers(string spName) 
     { 
      List<Customer> customers = new List<Customer>(); 

      SqlCommand cmd = new SqlCommand(); 
      cmd.Connection = con; 
      cmd.CommandType = CommandType.StoredProcedure; 
      cmd.CommandText = spName; 
     } 

我知道,使用使用I數據讀取器可以得到像這樣的數據庫中的值

IDataReader reader = cmd.ExecuteReader(); 

      while (reader.Read()) 
      { 
       Customer cus = new Customer(); 

       cus.Name = reader["cus_name"].ToString(); 
       cus.Id = Convert.ToInt32(reader["cid"]); 

       customers.Add(cus); 
      } 

如何使用這種方案將數據重新插入數據庫?幫助將不勝感激。

+0

它是更新還是插入?使用SqlBulkCopy可以將數據表保存在數據庫中 – Sami

+0

@Sami將數據插入數據庫:) –

+0

@AshaneAlvis。看到這個http://stackoverflow.com/a/12939934/4873601 –

回答

2

在基地你必須做一個SQL插入命令插入數據庫。所以,你可以嘗試以下。此方法將獲取列表和表名作爲參數。循環反射內部用於將值插入到鍵值對列表中。

public static bool Insert(List<YourModel> datas, string table) 
{ 
    bool result = false; 
    List<KeyValuePair<string, string>> values = new List<KeyValuePair<string, string>>(); 

    SqlConnection con = new SqlConnection("your connection string"); 
    con.Open(); 

    try 
    { 
     foreach (var data in datas) 
     { 

      values.Clear(); 
      foreach (var item in data.GetType().GetProperties()) 
      {   
       values.Add(new KeyValuePair<string, string>(item.Name, item.GetValue(data).ToString())); 
      } 

      string xQry = getInsertCommand(table, values); 
      SqlCommand cmdi = new SqlCommand(xQry, con); 
      cmdi.ExecuteNonQuery(); 
     } 
     result = true; 
    } 
    catch(Exception ex) 
    { throw ex; } 
    finally { con.Close(); } 
    return result; 
} 

在下面的方法中,鍵值對列表將被傳遞給另一個函數來進行插入命令。

private static string getInsertCommand(string table, List<KeyValuePair<string, string>> values) 
{ 
    string query = null; 
    query += "INSERT INTO " + table + " ("; 
    foreach (var item in values) 
    { 
     query += item.Key; 
     query += ", "; 
    } 
    query = query.Remove(query.Length - 2, 2); 
    query += ") VALUES ("; 
    foreach (var item in values) 
    { 
     if (item.Key.GetType().Name == "System.Int") // or any other numerics 
     { 
      query += item.Value; 
     } 
     else 
     { 
      query += "'"; 
      query += item.Value; 
      query += "'"; 
     } 
     query += ", "; 
    } 
    query = query.Remove(query.Length - 2, 2); 
    query += ")"; 
    return query; 
}