简体   繁体   中英

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#

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM