2016-08-18 68 views
1

我有保存任務等級:如何數據綁定DataTable添加到自定義對象的列表

class Task{ 
    public string Description; 
    public DateTime StartDate; 
    public DateTime EndDate; 
} 

我有一個名爲「任務」 DataTable SQLite數據庫:

DataTable.Rows[0]["Description"].ToString() // "Draw a cat" 
DataTable.Rows[0]["BeginDate"].ToString() // "2016-08-17 9:47:22 AM" 
DataTable.Rows[0]["EndDate"].ToString() // "2016-08-17 11:22:37 AM" 

我可以創建從DataTable填充的List<Task>嗎?

我可以在List<Task>上添加一個新的Task並讓它更新DataTable?

+0

您可以將實體框架與SQLite數據庫結合使用。 – Kinetic

+0

我意識到沒有什麼「盒子」,但其他人已經寫了一些擴展方法來做到這一點。例如:http://codereview.stackexchange。com/a/56857/20216 –

+0

如果根據此問題的最後一個版本存在數據庫,爲什麼要創建Task對象? DataRow可以表示一個'Task',你可以通過添加一行來創建一個新的。 – Plutonix

回答

1

我可以創建從DataTable填充的列表嗎?

你需要這樣的代碼做要緊:

// Creates IEnumerable<DataRow> 

var taskDataTableEnumerable = taskDataTable.AsEnumerable(); 

List<Task> myTaskList = 
    (from item in taskDataTableEnumerable 
    select new Task{ 
     Description = item.Field<string>("DescriptionColumnName"), 
     StartDate = item.Field<DateTime>("StartDateColumnName"), 
     EndDate = item.Field<DateTime>("EndDateColumnName") 
    }).ToList(); 

我能添加新任務到Listand有它更新的DataTable?

是的,你可以,你有以下選擇:

或者

  • 你可以簡單地創建一個新的DataRow現有的表如下:

     DataRow taskDataRow = taskDataTable.NewRow(); 
    
  • 來自新添加的任務對象的taskDataRow添加數據,使用類似代碼:

     taskDataRow["DescriptionColumnName"] = taskObject.Description 
         taskDataRow["StartDateColumnName"] = taskObject.StartDate 
         taskDataRow["EndDateColumnName"] = taskObject.EndDate 
    

這樣新加入的Task對象添加到列表是也作爲DataRow添加到DataTable,如果FastMember不適用於您的用例,並且您需要不同的選項,則可能計劃使用自定義代碼,如下面的所有type T屬性將被轉換爲DataTable與相應的列名,可以爲字段添加的選擇,如果需要,它是目前的性質:

public static DataTable CreateTable<TDataTable>(this IEnumerable<TDataTable> collection) 
    { 
     // Fetch the type of List contained in the ParamValue 
     var tableType = typeof(TDataTable); 

     // Create DataTable which will contain data from List<T> 
     var dataTable = new DataTable(); 

     // Fetch the Type fields count 
     var columnCount = tableType.GetProperties().Count(); 

     var columnNameMappingDictionary = new Dictionary<string, string>(); 

     // Create DataTable Columns using table type field name and their types 
     // Traversing through Column Collection 
     for (var counter = 0; counter < columnCount; counter++) 
     { 
      var propertyInfo = tableType.GetProperties()[counter];     

      // Fetch DataParam attribute 
      var dataParameterAttribute = propertyInfo.GetDataParameterAttribute(); 

      // Datatable column name based on DataParam attribute 
      var columnName = (dataParameterAttribute != null) ? dataParameterAttribute.Name : propertyInfo.Name; 

      columnNameMappingDictionary.Add(propertyInfo.Name, 
       (dataParameterAttribute != null) ? dataParameterAttribute.Name : propertyInfo.Name); 

      // Fetch the current type of a property and check whether its nullable type before adding a column 
      var currentType = tableType.GetProperties()[counter].PropertyType; 

      dataTable.Columns.Add(columnName, Nullable.GetUnderlyingType(currentType) ?? currentType); 
     } 

     // Return parameter with null value 
     if (collection == null) 
      return dataTable; 

     // Traverse through number of entries/rows in the List 
     foreach (var item in collection) 
     { 
      // Create a new DataRow 
      var dataRow = dataTable.NewRow(); 

      foreach (var columnName in columnNameMappingDictionary.Select(propertyinfo => propertyinfo.Value)) 
      { 
       dataRow[columnName] = item.GetType().GetProperty(columnName).GetValue(item) ?? DBNull.Value; 
      } 
      // Add Row to Table 
      dataTable.Rows.Add(dataRow); 
     } 

     return (dataTable); 
    } 

//數據參數屬性

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] 
    public class DataParamAttribute : Attribute 
    { 
     /// <summary> 
     /// Gets or sets the name. 
     /// </summary> 
     public string Name { get; set; } 

     /// <summary> 
     /// Initializes a new instance of the <see cref="DataParamAttribute"/> class. 
     /// </summary> 
     /// <param name="name"> 
     /// The name. 
     /// </param> 
     public DataParamAttribute(string name) 
     { 
      this.Name = name; 
     } 
    } 

//取DataParameter屬性

public static DataParamAttribute GetDataParameterAttribute(this PropertyInfo propertyInfo) 
     { 
      DataParamAttribute mappedAttribute = null; 

      // Get list of Custom Attributes on a property 
      var attributeArray = propertyInfo.GetCustomAttributes(false); 

      // Column mapping of the ParameterAttribute 
      var columnMapping = 
       attributeArray.FirstOrDefault(attribute => attribute.GetType() == typeof(DataParamAttribute)); 

      if (columnMapping != null) 
      { 
       // Typecast to get the mapped attribute 
       mappedAttribute = columnMapping as DataParamAttribute; 
      } 
      return mappedAttribute; 
     } 
相關問題