如何在Linq中表示SQL查询

时间:2014-04-24 04:54:12

标签: c# sql linq

我在SQL中有简单的查询但是在linq中转换有困难。我是linq的新手。

我的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 个答案:

答案 0 :(得分: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 });

如果您正在使用Entity Framework并且导航属性设置正确,您可以将其简化为类似的内容......

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