Using LINQ to Dataset in an .aspx page (Jonathan Aneja)

Recently I got a customer question about how to use LINQ to Dataset in an .aspx file.  The compiler was complaining that it couldn’t find the AsEnumerable method that allows LINQ to work over a DataTable (“AsEnumerable is not a member of ‘DataTable'”).  The code he sent looks correct, so why is the compiler not picking up the extension method (defined in System.Data.DataSetExtensions.dll)?


<%@ Page Language=”vb” AutoEventWireup=”false” CodeBehind=”Default.aspx.vb” Inherits=”WebApplication6._Default” %>


<%@ Import Namespace=”System.Linq” %>

<%@ Import Namespace=”System.Data.DataSetExtensions” %>


<script runat=”server”>


    Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load


        Dim ds As New System.Data.DataSet



        ‘error here

        Dim query = From row In ds.Tables(0).AsEnumerable() Select row


    End Sub




After staring at that for a while and thinking it was a bug in the compiler, I forwarded it on to some of the ADO guys.  It turns out the fix is simple, change the import to say “System.Data” instead of “System.Data.DataSetExtensions”.  If you open up Reflector the reason’s obvious: the AsEnumerable extension method is defined in the System.Data namespace of the System.Data.DatasetExtensions assembly.  There is a System.Data.DatasetExtensions namespace as well, but it’s not the one that contains the extension methods.


I can see why they designed it this way, by putting it in System.Data you can use LINQ right out of the box on your existing Datasets, since typically System.Data is already imported.  Unfortunately that wasn’t the case here.


Here’s the right line of code to use:

<%@ Import Namespace=”System.Data” %>


As an aside, you don’t actually have to insert the explicit call to AsEnumerable when working with LINQ to Dataset (in VB), I’ll explain why in a blog post tomorrow.