Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

Convert LINQ to Entity Result to a DataTable

4.67/5 (3 votes)
20 Apr 2011CPOL 28.5K  
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)