user9202791
user9202791

Reputation:

Entity Framework to Datatable

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#

Upvotes: 4

Views: 8073

Answers (1)

FractalCode
FractalCode

Reputation: 380

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

Upvotes: 5

Related Questions