将SQL Join Query转换为Linq查询

时间:2014-04-21 06:56:05

标签: c# sql sql-server linq

我想加入不同的列,输出将使用linq

|     Name     |    Address   |     Cellphone    |     Email      | 
|     John     |     NY       |       n/a        |   johndoe@y.c  |
|     John     |     NY       |    123456781     |       n/a      |

我希望我的输出是一个组合

|     Name     |    Address   |     Cellphone    |     Email      | 
|     John     |     NY       |     123456781    |   johndoe@y.c  |

我在SQL服务器上试过它,这是回答所需输出的查询

select a.ID, a.Name , a.Address ,(
SELECT wc1.[Values]
  FROM Contact as wc1 where wc1.infoID = a.ID and wc1.ContactTypeID = 56) as Email
  ,(
SELECT wc1.[Values]
  FROM Contact as wc1 where wc1.infoID = a.ID and wc1.ContactTypeID = 59) as Cellphone
  from Info as a where a.ID = 100

还在Linq上尝试了它,但它产生了具有相同ID的不同行

var an = (from a in db.Info
          join b in db.Contact on a.ID equals b.InfoID
          where b.ContactTypeID == 56
             || b.ContactTypeID == 59
          select new
          {
              a.ID,
              a.LastName,
              a.FirstName,
              a.MiddleName,
              b.ContactTypeID,
              b.Values
          }).ToList();

List<InfoList> wlist = new List<InfoList>();

foreach (var row in an)
{
    InfoList ci = new InfoList
        {
            ID = row.ID,
            Name = row.FirstName + " " + row.MiddleName + " " + row.LastName,
            ContactType = GetLookupDisplayValById(row.ContactTypeID),
            ContactValue = row.Values
        };
    wlist.Add(ci);
}

return Json(wlist.ToList(), JsonRequestBehavior.AllowGet);

有人可以帮我翻译成Linq声明吗

2 个答案:

答案 0 :(得分:0)

您的SQL不使用JOIN,那么为什么要尝试在LINQ中引入它?

var an = (from a in db.Info
          select new
          {
              a.ID,
              a.LastName,
              a.FirstName,
              a.MiddleName,
              Email = db.Contact.FirstOrDefault(b => b.InfoID == a.ID && b.ContactTypeIF == 56).Values,
              Cellphone = db.Contact.FirstOrDefault(b => b.InfoID == a.ID && b.ContactTypeIF == 59).Values,
          }).FirstOrDefault(x => x.ID == 100);

答案 1 :(得分:0)

您可以使用Pivot表中提到的链接显示如何使用它:http://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query