How to deal with a flaw in System.Data.DataTableExtensions.CopyToDataTable()

Posted by andy on Stack Overflow See other posts from Stack Overflow or by andy
Published on 2009-03-11T23:27:46Z Indexed on 2010/03/11 17:44 UTC
Read the original article Hit count: 238

Filed under:
|
|
|

Hey guys, so I've come across something which is perhaps a flaw in the Extension method .CopyToDataTable.

This method is used by Importing (in VB.NET) System.Data.DataTableExtensions and then calling the method against an IEnumerable. You would do this if you want to filter a Datatable using LINQ, and then restore the DataTable at the end.

i.e:

Imports System.Data.DataRowExtensions
	Imports System.Data.DataTableExtensions

	Public Class SomeClass
    		Private Shared Function GetData() As DataTable
        		Dim Data As DataTable

        		Data = LegacyADO.NETDBCall


        		Data = Data.AsEnumerable.Where(Function(dr) dr.Field(Of Integer)("SomeField") = 5).CopyToDataTable()


        		Return Data

    		End Function
	End Class

In the example above, the "WHERE" filtering might return no results. If this happens CopyToDataTable throws an exception because there are no DataRows.

Why?

The correct behavior should be to return a DataTable with Rows.Count = 0.

Can anyone think of a clean workaround to this, in such a way that whoever calls CopyToDataTable doesn't have to be aware of this issue?

System.Data.DataTableExtensions is a Static Class so I can't override the behavior....any ideas? Have I missed something?

cheers

UPDATE:

I have submitted this as an issue to Connect. I would still like some suggestions, but if you agree with me, you could vote up the issue at Connect via the link above

cheers

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about vb.net