4

Is there any way to convert an Entity Framework query result to a DataTable?

or

Is there any way to convert contemporaneity table to DataTable? Using C#

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 3
    https://stackoverflow.com/a/21672867/284240 – Tim Schmelter May 29 '18 at 10:22
  • 1
    What for? For the love of God, tell me why you needed this. DataTable was needed before the advent of ORM. And now EF gives you a filled collection of strongly typed objects, which is much more convenient than DataTable. – Alexander Petrov May 30 '18 at 00:02
  • 1
    yeah i know still i want to know is there any in built function to do so or not –  May 30 '18 at 07:37

1 Answers1

4

You can use some reflection and generics to build the DataTable.

For example:

   public static DataTable CreateDataTable<T>(IEnumerable<T> entities)
    {
        var dt = new DataTable();

        //creating columns
        foreach (var prop in typeof(T).GetProperties())
        {
            dt.Columns.Add(prop.Name, prop.PropertyType);
        }

        //creating rows
        foreach (var entity in entities)
        {
            var values = GetObjectValues(entity);
            dt.Rows.Add(values);
        }


        return dt;
    }

public static object[] GetObjectValues<T>(T entity)
    {
        var values = new List<object>();
        foreach (var prop in typeof(T).GetProperties())
        {
            values.Add(prop.GetValue(entity));
        }

        return values.ToArray();
    }
FractalCode
  • 360
  • 1
  • 4