我有特定的SQL表达式:
{
select * from courceMCPD.dbo.Contact c
where c.cID in ( select cId from courceMCPD.dbo.Friend f where f.cId=5)
}
我想获得获得相同结果的LINQ表达式。
提前谢谢。
答案 0 :(得分:4)
这听起来像是等同于:
var friendIds = from friend in db.Friends
where friend.ContactId == 5
select friend.ContactId;
var query = from contact in db.Contacts
where friendIds.Contains(contact.Id)
select contact;
(有很多不同的方式来表示查询,但这是我能想到的最简单的方法。)
在特定字段上执行连接并且还要求该字段必须具有特定值,这是非常奇怪的... ...之间没有非常那和:
var query = db.Contacts.Where(c => c.Id == 5);
...唯一的区别是该特定联系人是否有任何朋友条目。
编辑:Smudge在评论中为查询提供了另一个选项,所以我将其推广到这个答案......
var query = db.Contacts.Where(c => c.Friends.Any(f => f.cId == 5))
这假设您已在Friends
实体中定义了适当的Contacts
关系。
答案 1 :(得分:2)
使用lambda表达式:
var query = dc.Contact
.Where(c => dc.Friend.Select(f => f.cId).Contains(i.cID))
.Where(c => c.cId == 5);
用户“查询”语法:
var query = from c in dc.Contact
where (from f in dc.Friend select f.cID).Contains(c.cId)
where c.cId == 5
select c;
答案 2 :(得分:1)
你没有指定VB / C#所以我要去VB = P
Dim results As IEnumerable(Of yourEntities.Contact) =
(From c In yourContextInstance.Contacts Where (From f In yourContextInstance.Friends
Where f.cId = 5 Select f.cId).Contains(c.cID))
显然,Jon的答案有效,这个查询(我相信)就像你的T-SQL Closer。