Reimu Lyu
Reimu Lyu

Reputation: 31

how to translate a linq expression into sql string use c# code

how to translate a linq expression for example

var query = (from article in ArticleRepository.GetAll()
            join read in ArticleReadRepository.GetAll() on read.ArticleId equals article.Id
            where article.Id>10
            select new 
            {
                article.Title,
                read.ReadCount
            }).ToList();

into sql string

select article.Title,
       read.ReadCount 
       from ArticleTable as article 
       join ArticleReadTable as read on read.ArticleId = article.Id 
       where article.Id>10

use c# code

Upvotes: 0

Views: 558

Answers (1)

Richa Garg
Richa Garg

Reputation: 1926

Print query.ToString() and you will see the query formed by the LINQ expression

For example,

var query = from emp in v.Employees
            select emp;
var sqlQuery = query.ToString();
Console.WriteLine(sqlQuery);

The result will be:

SELECT 
[Extent1].[ID] AS [ID], 
[Extent1].[Name] AS [Name]
FROM [dbo].[Employee] AS [Extent1]

Upvotes: 2

Related Questions