2016-08-16 19 views
0

如何例如如何翻譯LINQ表達式到SQL字符串使用C#代碼

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(); 

LINQ表達式翻譯成SQL字符串

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

使用C#代碼

回答

2

打印query.ToString()和您將看到由LINQ表達形成的查詢

例如,

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

結果將是:

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

實際上,我想知道query.ToString()的實現......好吧,我會看到它的源代碼。 –

+0

您可以從'query.ToString'中將其作爲字符串進行檢索並將其作爲sql查詢進行觸發。 –

+0

@ReimuLyu如果它解決了您的問題,請將其標記爲答案 –