简体   繁体   中英

How to use CopyToDataTable() method in LINQ successfully using below example only?

I have been trying something with LINQ to get all the data from a table customers in a data table. I have used SQL to LINQ class here.

SampleDataContext sdc = new SampleDataContext();
            DataTable Cust = new DataTable();
            //var query = from c in sdc.customers
            //                       select c;
            var query = (IEnumerable<DataRow>)sdc.customers.Select(c => c);
            Cust = query.CopyToDataTable();
            Console.WriteLine(Cust);

Now when I run this, I get an exception:

'Unable to cast object of type 'System.Data.Linq.DataQuery`1[BasicLearning.customer]' to type
'System.Collections.Generic.IEnumerable`1[System.Data.DataRow]'.'

Why am I getting this exception? ANS - from my understanding, which may be wrong, the (IEnumerable<DataRow>) casting in above logic won't work because the result set is not an IEnumberable but IQueryable. But I am not sure if I understand this exception correctly.

So, here I am stuck now, on how to get this code running. I want to use CopyToDataTable() method. But Casting is not working.

It would be great if anyone could help me understand what I am doing wrong here and how to correct it.

as @Svyatoslav Danyliv mention you need to convert object to table. there is an extention which dynamically convert object to datatable.


void Main()
{
    
    DataTable Cust = new DataTable();
    //var query = from c in sdc.customers
    //                       select c;
    var query = Customers.Select(c => c).ConvertClassToDataTable<Customer>().AsEnumerable();
    
    Cust = query.CopyToDataTable();
    Console.WriteLine(Cust);
}


public static class Extensions
{
    public static DataTable ConvertClassToDataTable<T>(this IEnumerable<T> list)
    {
        Type type = typeof(T);
        var properties = type.GetProperties();

        DataTable dataTable = new DataTable();
        foreach (PropertyInfo info in properties)
        {
            dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
        }

        foreach (T entity in list)
        {
            object[] values = new object[properties.Length];
            for (int i = 0; i < properties.Length; i++)
            {
                values[i] = properties[i].GetValue(entity);
            }

            dataTable.Rows.Add(values);
        }

        return dataTable;
    }

}

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