Click here to Skip to main content
15,881,803 members
Articles / Programming Languages / Visual Basic
Alternative
Tip/Trick

Convert LINQ to Entity Result to a DataTable

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
20 Apr 2011CPOL 27.5K   5   3
Very good stuff. Learned me a lot about how to access to the physical structure of the query.There is also a CopyToDataTable : http://msdn.microsoft.com/en-us/library/bb386921.aspx[^]And for the record here is a C# version:protected DataTable EntityToDatatable(IQueryable Result,...
Very good stuff. Learned me a lot about how to access to the physical structure of the query.
There is also a CopyToDataTable : http://msdn.microsoft.com/en-us/library/bb386921.aspx[^]

And for the record here is a C# version:
protected DataTable EntityToDatatable(IQueryable Result, ObjectContext ctx)
        {
            try
            {
                EntityConnection conn = ctx.Connection as EntityConnection;
                using (SqlConnection SQLCon = new SqlConnection(conn.StoreConnection.ConnectionString))
                {
                    ObjectQuery query = Result as ObjectQuery;
                    using (SqlCommand Cmd = new SqlCommand(query.ToTraceString(), SQLCon))
                    {
                        foreach (var param in query.Parameters)
                        {
                            Cmd.Parameters.AddWithValue(param.Name, param.Value);
                        }
                        using (SqlDataAdapter da = new SqlDataAdapter(Cmd))
                        {
                            using (DataTable dt = new DataTable())
                            {
                                da.Fill(dt);
                                return dt;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

License

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


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

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 919758621-Oct-12 20:45
Member 919758621-Oct-12 20:45 
GeneralReason for my vote of 4 nice work jonx Pin
ace98902-Aug-11 21:43
ace98902-Aug-11 21:43 
GeneralReason for my vote of 5 Thanks for Conversion! Pin
Gandalf_TheWhite20-Apr-11 19:11
professionalGandalf_TheWhite20-Apr-11 19:11 

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.