2014-04-24 47 views
0

我在SQL中有簡單的查詢,但在linq中轉換時遇到困難。我是linq新手。如何在Linq中表示SQL查詢

我的SQL SELECT語句如下:

select CM.CategoryName 
from dbo.utblCategoryMaster as CM 
where CM.ParentCategoryID in 
    (select CategoryID from dbo.utblCategoryMaster where CategoryName='Events') 

我知道這是簡單和容易。我試過這個

var result = from objutblCategoryMaster in db.utblCategoryMasters 
    select new 
    { 
     CategoryID = objutblCategoryMaster.CategoryID, 
     CategoryName = db.utblCategoryMasters.Where(x => x.ParentCategoryID == objutblCategoryMaster.CategoryID && x.CategoryName=="Events") 
    }; 
return result.CopyToDataTableExt(); 
+1

你有什麼具體的問題Chettri – Neel

+0

我覺得難度在linq中轉換我的sql查詢。我只想將我的sql查詢轉換爲linq –

回答

1

你可以用連接得到結果。

var result = db.utblCategoryMasters 
       .Join(db.utblCategoryMasters.Where(c => c.CategoryName=="Events"), 
        cm => cm.ParentCategoryId, 
        c => c.CategoryId, 
        (cm, c) => new { cm.CategoryId, cm.CategoryName }); 

如果您使用實體框架和導航屬性設置正確,可以將其簡化爲這樣的事情...

var result = db.utblCategoryMasters 
       .Where(cm => cm.ParentCategory.CategoryName == "Events") 
       .Select(cm => new { cm.CategoryId, cm.CategoryName }); 
+0

謝謝安東尼楚 –