LINQ query IEnumerable for IEnumerable results in null c# datatable linq sqlbulkcopy

Question

Why is my LINQ query ("rows") showing up as a null when it seems like I have plenty of data ("waypoints")?

I'm doing an insert of ~20k records and rather than go through Entity Framework I've opted for SqlBulkCopy, which seems to mean I need a datatable. I'm trying to get an IEnumerable into IEnumberable as that seems to be the only way to get CopyToDataTable().

I was copying the syntax in this answer, and you can see in my debugger that I have plenty of objects in my original list but IEnumerable is null.

enter image description here

Same code, maybe easier to read:

    IEnumerable<DataRow> rows =
            (from w in waypoints.AsEnumerable()
            select w)  as IEnumerable<DataRow>;

    DataTable table = rows.CopyToDataTable();

The "rows" variable is returning as null.

Accepted Answer

You are trying to typecase an IEnumerable<Waypoint> as an IEnumerable<DataRow>, which is not going to work unless your Waypoint class is derived from DataRow, which I assume it's not. The documentation for the CopyToDataTable method is pretty clear:

The parameter T of the input parameter source can only be of type DataRow or a type derived from DataRow.

You are going to have to make your data table the long way, unfortunately. Make a new blank DataTable, add columns to it's Columns collection, then add rows to it's Rows collection.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why