65.9K
CodeProject is changing. Read more.
Home

Convert LINQ to Entity Result to a DataTable

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (3 votes)

Apr 20, 2011

CPOL
viewsIcon

28514

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;
            }
        }