steve steve - 7 months ago 80
ASP.NET (C#) Question

How to convert IQueryable to DataTable

I wrote the query using LinQ and I used the

method. At that line it is showing implicit conversion type error from my database type to

var query = from i in dbContext.Personaldetails
where i.ID == 1
select i;

return query.CopyToDataTable();

Any suggestions?


CopyToDataTable requires collection of DataRow objects. See How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow to solve this problem.

UPDATE: If your entity has nullable field, you can modify ObjectShredder.ExtendTable method. Find place where new columns are added to table, and remove second parameter, which provides type of data in column (DataColumn class does not support nullable data types):

foreach (PropertyInfo p in type.GetProperties())
    if (!_ordinalMap.ContainsKey(p.Name))
        DataColumn dc = table.Columns.Contains(p.Name) ? table.Columns[p.Name]
            // do not provide column type
            : table.Columns.Add(p.Name); 

        _ordinalMap.Add(p.Name, dc.Ordinal);