2014-04-28 139 views
5

我正在使用EF 6開發MVC4網絡應用程序。我正在使用EF代碼第一種方法(在全新的數據庫上)。所以我有我在EF中使用的模型類。
EF Codefirst和RDLC報告

現在我需要創建一些RDLC報告。爲此,我需要創建一個數據集。那麼如何使用我的模型類創建數據集?我需要將模型類與數據集進行關聯。

我的最終目標是使用我的ef模型設計數據並將其填充到我的報告中。

非常感謝

回答

3

通常EF不支持數據集。如果你想用EF加載的數據填充數據集,那麼你必須提供你自己的功能。在這裏,我來舉一個例子如何從查詢得到的結果填充DataTable對象:

public static class IEnumerableExtensions 
{ 
    public static DataTable ToDataTable<TEntity>(this IEnumerable<TEntity> entities) 
    { 
     DataTable table = new DataTable(); 
     IEnumerable<PropertyInfo> properties = typeof(TEntity) 
      .GetProperties() 
      .Where(p => !p.PropertyType.IsClass || p.PropertyType == typeof(string)) 
     foreach(string propertyName in properties.Select(p => p.Name)) 
     { 
      table.Columns.Add(propertyName); 
     } 
     foreach(object item in entities) 
     { 
      List<object> propertiesValues = new List<object>(); 
      foreach (PropertyInfo property in properties) 
      { 
       propertiesValues.Add(property.GetValue(item)); 
      } 
      table.Rows.Add(propertiesValues.ToArray()); 
     } 
     return table; 
    } 
} 

您可以使用那麼這個擴展方法如下:

DataTable table = context.People.ToDataTable(); 

如果你想實現表之間的關係,則你必須做的邏輯將會更復雜。您應該使用DataTable對象的ChildRelations屬性將它們與關係綁定。然後你可以將DataTable對象插入到DataSet中。