如何将此T-SQL转换为LINQ

时间:2012-07-09 04:46:59

标签: c# sql linq linq-to-entities

我有以下SQL语句

    SELECT [CodeHouse]
          ,[CodeReq]
          ,[Address]
      FROM [ShahrdariProject].[dbo].[House]
      where [CodeReq] in
      (select [CodeReq] From [ShahrdariProject].[dbo].[HouseOwner] where [Name] = 'Alex' )

有人可以帮助我将此声明转换为LINQ吗?

4 个答案:

答案 0 :(得分:2)

这个SQL:

 SELECT [CodeHouse]
      ,[CodeReq]
      ,[Address]
  FROM [ShahrdariProject].[dbo].[House]
  where [CodeReq] in
  (select [CodeReq] From [ShahrdariProject].[dbo].[HouseOwner] 
   where [Name] = 'Alex' )

相当于这个Linq:

var q = from h in db.Houses
        where db.HouseOwners.Any(x => x.Name == "Alex" && x.CodeReq == h.CodeReq)
        select h;

答案 1 :(得分:1)

using(var dbContext = new /**Your Linq DataContext class here**/())
{

    var results = dbContext.House.Join(
                dbContext.HouseOwner.Where(ho => ho.Name == "Alex"), 
                h => h.CodeReq, 
                ho => ho.CodeReq,
                (h, ho) => select new { h.CodeHouse, h.CodeReq, h.Address }).ToArray();
}

编辑:根据您的查询,我认为使用JOIN而不是使用IN来表达查询

答案 2 :(得分:1)

List<string> codeReq = new List<string>();
using(DemoDataContext db = new DemoDataContext()){
var houses = from h db.Houses where codeReq.Contains(h.codeReq) selec h;
}

答案 3 :(得分:1)

尝试使用以下代码,我相信这可以解决您的问题

var result = from house in db.Houses
    where db.HouseOwners.Any(z => z.Name == "Alex" && z.CodeReq == house.CodeReq)
    select house;

享受......