SQL查询转换为LINQ

时间:2014-08-17 16:49:56

标签: sql-server asp.net-mvc linq asp.net-mvc-4

如何使用LINQ编写此SQL查询?

我尝试了一些想法,但无法弄清楚:

  SELECT  id , Email
  FROM Customer
  WHERE Customer.Id IN 
  (SELECT CustPeople.PeopleID
  FROM  CustPeople    WHERE MemID = 1)    

Customer

    Id  Email        
   --------------------------
    1   johnDoe@aol.com
    12  billGates@yahoo.com
    11  charlieParker@aol.com

CustPeople

    Id  MemID   PeopleID
    ----------------------
    1   1       11
    2   1       12
    3   4       163

结果:

    11  charlieParker@aol.com
    12  billGates@yahoo.com

我使用连接吗?有没有办法在linq中创建子查询?

   var people = from c in _custRepository.Table
                join p in _custPeopleRepository.Table on c.Id equals p.MemID
                ???

1 个答案:

答案 0 :(得分:1)

对集合的

Contains调用将被翻译为IN子句:

var people = from c in _custRepository.Table
             where _custPeopleRepository.Table
                                        .Where(x => x.MemID == 1)
                                        .Select(x => x.PeopleID)
                                        .Contains(c.Id)
             select new { c.Id, c.Email };