EF Codefirst和RDLC报表

5
我正在开发一个使用EF 6的MVC4 Web应用程序。我正在使用EF先代码方法(在全新的数据库上)。因此,我有模型类,我在EF中使用它们。
现在,我需要创建一些RDLC报表。为此,我需要创建一个数据集。那么,如何使用我的模型类创建数据集?我的模型类之间存在关系,这些关系需要传递到数据集中。
我的最终目标是使用我的EF模型设计和填充报表数据。
谢谢!
1个回答

3

一般来说,EF不支持DataSets。如果您想使用EF加载的数据填充DataSets,则必须为此提供自己的功能。这里我提供一个示例,说明如何从查询结果中填充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中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接