Click here to Skip to main content
15,891,431 members
Articles / Programming Languages / Visual Basic
Tip/Trick

Convert LINQ to Entity Result to a DataTable

Rate me:
Please Sign up or sign in to vote.
5.00/5 (7 votes)
22 Mar 2011CPOL 58.3K   12   7

Introduction

This article helps converting LINQ to Entity result to a data table. This can be very useful if you are moving to entity framework and still want to support existing methods, write a normal Linq to entity syntax, then with a simple extension method convert it to a data table. Note that the Query is executed once on the server and there is no need to loop the result and create the data table which takes too much time.


Using the code

These two extension methods help in getting the data table directly form the result.


VB
Imports System.Data.Objects 
Imports System.Linq.Expressions
Imports System.Data.SqlClient

//Public Module EntityToDataTable

//<extension()> _
Public Function EntityToDatatable(ByVal Result As IQueryable, ByVal Ctx As  ObjectContext) As DataTable
    Try
        Using SQLCon As New SqlConnection(CType(Ctx.Connection, EntityConnection).StoreConnection.ConnectionString)
            Using Cmd As New SqlCommand(CType(Result, ObjectQuery).ToTraceString, SQLCon)
                For Each Param As ObjectParameter In CType(Result, ObjectQuery).Parameters
                    Cmd.Parameters.AddWithValue(Param.Name, Param.Value)
                Next
                Using DA As New SqlDataAdapter(Cmd)
                    Using DT As New DataTable
                        DA.Fill(DT)
                        Return DT
                    End Using
                End Using
            End Using
        End Using
    Catch
        Throw
    End Try
End Function

//<extension()> _
Public Sub EntityToDatatable(ByVal Result As IQueryable, ByVal Ctx As ObjectContext, ByVal DT As DataTable)
     Try
         Using SQLCon As New SqlConnection(CType(Ctx.Connection, EntityConnection).StoreConnection.ConnectionString)
             Using Cmd As New SqlCommand(CType(Result, ObjectQuery).ToTraceString, SQLCon)
                 For Each Param As ObjectParameter In CType(Result, ObjectQuery).Parameters
                     Cmd.Parameters.AddWithValue(Param.Name, Param.Value)
                 Next
                 Using DA As New SqlDataAdapter(Cmd)
                     DA.Fill(DT)
                 End Using
             End Using
         End Using
     Catch
         Throw
     End Try
 End Sub

  //End Module          

Hope it helps.

Development to me is a pleasure more than a job.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer CME Offshore
Lebanon Lebanon
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionNot so sure Pin
Daniel C31-May-15 15:40
Daniel C31-May-15 15:40 
Everyone else probably has more experience coding that I do but this is really tough to use. Some stuff I just don't understand and some just doesn't seem to work. My biggest issues are that there are no examples of how to implement this function. A nice simple example of a small vb.net Entity Framework app where someone wants to run a simple linq query and get the results into a datatable. The example should explain everything including the infuriating ObjectContext creation.

The biggest problem though is that this thing won't convert a linq query. I also don't know why the query argument for this function is called "result" but maybe I just don't understand it. Anyway here is the line of code from the author's example:
VB
Using Cmd As New SqlCommand(CType(Result, ObjectQuery).ToTraceString, SQLCon)

I have played with this for hours and can't get a linq query to Ctype into an ObjectQuery. Maybe there's a trick but I can't find it. Here is my example code:
VB
Private Shared m_carData As New CarEntities()

Dim query1 = From a In m_carData.Cars
             Select a.CarType.Name

Dim convertedquery = CType(query1, ObjectQuery)

If I run this or use the author's function I receive the following error:
System.InvalidCastException: Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[System.String]' to type 'System.Data.Objects.ObjectQuery'. at Car_Tracker.FrmHome.RefreshStaticLists() in C:\Users\Mike\Documents\Visual Studio 2013\Projects\Car Tracker\Car Tracker\FrmHome.vb:line 175


Or this code using Iqueryable which also fails:
VB
Private Shared m_carData As New CarEntities()

Dim query1 IQueryable(Of Car) = From a In m_carData.Cars
                                Select a

Dim convertedquery = CType(query1, ObjectQuery)

Error produced:
System.InvalidCastException: Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[System.String]' to type 'System.Linq.IQueryable`1[Car_Tracker.Car]'.
   at Grow_Tracker.FrmHome.RefreshStaticLists() in C:\Users\Mike\Documents\Visual Studio 2013\Projects\Car Tracker\Car Tracker\FrmHome.vb:line 176


Any help getting this running would be fantastic as I really need this functionality. Sorry if I'm being a n00b.
Questioni have a problem Pin
ms_vb7-Oct-14 4:36
ms_vb7-Oct-14 4:36 
QuestionHow Can Use This? Pin
r. salehi29-May-13 7:19
r. salehi29-May-13 7:19 
AnswerRe: How Can Use This? Pin
Mohammad Al Hoss5-Jun-13 20:56
Mohammad Al Hoss5-Jun-13 20:56 
GeneralMy vote of 5 Pin
Dean Henderson3-Jul-12 11:17
Dean Henderson3-Jul-12 11:17 
GeneralReason for my vote of 5 very helpful.it makes my code run. Pin
awm00122-Mar-11 3:03
awm00122-Mar-11 3:03 
GeneralNot extension methods Pin
Henry Minute21-Mar-11 2:46
Henry Minute21-Mar-11 2:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.