iqueryable转DataTable分两种情况:

1.linq to sql

private DataTable convertToDT(m2SharpDataContext dc, IQueryable query)
{
    DataTable dt = new DataTable();
    if (query != null)
    {
        IDbCommand cmd = dc.GetCommand(query);
        SqlDataAdapter sda = new SqlDataAdapter();
        sda.SelectCommand = (SqlCommand)cmd;
        try
        {
            cmd.Connection.Open();
            sda.FillSchema(dt, SchemaType.Source);
            sda.Fill(dt);
        }
        finally
        {
            cmd.Connection.Close();
        }
    }
    return dt;
}

_ueditor_page_break_tag_

2.linq to entities

protected DataTable EntityToDatatable(IQueryable Result, M2FinancialEntities1 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;
    }
}

参考:http://www.codeproject.com/Tips/184675/Convert-LINQ-to-Entity-Result-to-a-DataTable

最后修改:2014 年 09 月 17 日
如果觉得我的文章对你有用,请随意赞赏