ExtensionMethod.NET Home of 819 C#, Visual Basic, F# and Javascript extension methods

Ori Samara

Extracts the underylying SQL query from an IQueryable datatype

Source

/// <summary>
/// Extracts the underylying SQL query from an IQueryable datatype
/// </summary>
/// <param name="source">https://visualstudiomagazine.com/blogs/tool-tracker/2011/11/seeing-the-sql.aspx</param>
/// <returns>Returns a SQL Query in a string datatype</returns>
public static string ToSQLQuery<T>(this IQueryable<T> source)
{
    var x = IsNullOrEmpty(Convert.ToString(source)) ? "" : source.ToString().Replace("[Extent", "[D");
    return x;
}

Example

var res = new List<EntityName>();
string query = "";
using (Entities sp = new Entities())
{
    var q = sp.EntityName;
    query = q.ToSQLQuery();
    res = q.ToList();

}

return res;

Author: Ori Samara

Submitted on: 10 feb 2016

Language: C#

Type: IQueryable<T>

Views: 2090