phantom phantom - 3 months ago 16
C# Question

Displaying automatically generated SQL code from column sorting

I would want to be able to display those automatically generated SQL code on the database web page, when doing a primary sorting on a specific column in web grid.

For Instance, if you click on any column header on a database web page, the selected column will be sorted as a primary sorting column and then display the result in ascending or descending order.

My question is, would it be possible to retrieve those automatically generated SQL code behind the sorting process and display them onto the web page ? can't seems too find any resource about this. Any reading that can be used as a reference will be much appreciated.

Answer

You can easily do it by using Context Log property.

using (var context = new BlogContext()) 
{ 
    context.Database.Log = Console.Write; 

    // Your code here... 
}

You can use it for Logging to different places.Such as log to memory,file and by using different kinds of TextWriter.

public class MyLogger 
{ 
    public void Log(string component, string message) 
    { 
        Console.WriteLine("Component: {0} Message: {1} ", component, message); 
    } 
}

//This could be hooked up to the EF Log property like this:

var logger = new MyLogger(); 
context.Database.Log = s => logger.Log("MyEFApp", s);

You can refer this doc for more info : Logging and Intercepting Database Operations