Extract sql query from LINQ expressions

后端 未结 5 1564
太阳男子
太阳男子 2020-12-15 22:06

Is it possible to extract sql statements from LINQ queries ?

Say, I have this LINQ expression.

        string[] names =
            ne         


        
5条回答
  •  别那么骄傲
    2020-12-15 22:27

    EDIT #2: the update and clarification has completely changed the question.

    It sounds like you're reinventing the wheel and trying to accomplish what LINQ to SQL and LINQ to Entities already accomplish. For example, the providers examine the expression trees and map certain functions to SQL Server. You would be undertaking a large task that Microsoft has already provided us with and tested extensively.

    You would be much better off using existing ORM solutions, be it Microsoft's or NHibernate etc.


    EDIT #1: found it, I knew I saw something for this before but it eluded me.

    You can use the DataContext.GetCommand method to get the generated SQL:

    var query = dc.Persons.Take(1);
    string generatedSql = dc.GetCommand(query).CommandText;
    

    This example returns the following SQL from the AdventureWorks database:

    SELECT TOP (1) [t0].[BusinessEntityID], [t0].[PersonType], [t0].[NameStyle], [t0].[Title], [t0].[FirstName], [t0].[MiddleName], [t0].[LastName], [t0].[Suffix], [t0].[EmailPromotion], [t0].[AdditionalContactInfo], [t0].[Demographics], [t0].[rowguid] AS [Rowguid], [t0].[ModifiedDate] FROM [Person].[Person] AS [t0]


    Another option to determine the generated statements will be available in VS2010 via IntelliTrace (previously known as the Historical Debugger). For more information and screenshots see this blog post: Debugging LINQ to SQL queries using the Historical Debugger.

    That's only good during debugging though, and doesn't provide a way to access it programmatically.

提交回复
热议问题