Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Codefirst and RDLC Reports

I'm working on a MVC4 web app with EF 6. I'm using EF code first approach (on a brand new database). So i have the model classes which i use in EF.

Now i need to create some RDLC Reports. To do this i need to create a Dataset. So how can i create a dataset using my model classes? There are relationships between models classes which i need to carry to the dataset.

My ultimate goal is to design and populate data to my report using my ef models.

Thanks in Adance

like image 899
InsI Avatar asked Oct 21 '22 09:10

InsI


1 Answers

Generally EF does not support DataSets. If you want to populate DataSets with data loaded with EF then you've got to provide your own functionality for that. Here I present an example how to populate DataTable object from result obtained with query:

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;
    }
}

You might use then this extension method as follows:

DataTable table = context.People.ToDataTable();

If you want to implement relationships between tables then the logic you have to do will be more complicated. You should use ChildRelations property of DataTable objects to bind them with relations. Then your DataTable objects you might insert into DataSet.

like image 146
mr100 Avatar answered Oct 23 '22 01:10

mr100