Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server SQL到LINQ表达式_Sql Server_Linq - Fatal编程技术网

Sql server SQL到LINQ表达式

Sql server SQL到LINQ表达式,sql-server,linq,Sql Server,Linq,我有特定的SQL表达式: { select * from courceMCPD.dbo.Contact c where c.cID in ( select cId from courceMCPD.dbo.Friend f where f.cId=5) } 我想要得到得到相同结果的LINQ表达式 提前谢谢你。这听起来好像相当于: var friendIds = from friend in db.Friends where friend.ContactId ==

我有特定的SQL表达式:

{
select * from courceMCPD.dbo.Contact c 
where c.cID in ( select cId from courceMCPD.dbo.Friend f where f.cId=5)
}
我想要得到得到相同结果的LINQ表达式


提前谢谢你。

这听起来好像相当于:

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))
这假设您在
联系人
实体中定义了适当的
朋友
关系。

您没有指定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非常相似。

使用labda表达式:

var query = dc.Contact
        .Where(c => dc.Friend.Select(f => f.cId).Contains(i.cID))
        .Where(c => c.cId == 5);
用户“查询”语法:


实际上,我已经修改了我的,以便更接近你的,因为如果有多个好友记录,这是有区别的。然而,我已经为内部查询使用了一个单独的变量,以使事情更清楚(IMO)。公平的一个,尽管我认为您的上一个查询可能可以调整为非常干净,并包含整个功能(尽管对于多个lambda可能可读性较差)。你把你的答案改得和我的答案更一致,这没问题——真是荣幸;——)我同意你的观点,只是想知道(很抱歉,注释中的代码)var query=db.Contacts.Where(c=>c.Friends.Any(f=>f.cId==5))是否在c#(VB equiv)中工作,它会像你上次的查询那样工作,但也能确保朋友的存在吗?@Smudge202:是的,这应该工作得很好,而且是一个很好的等价物。如果有朋友的话,它应该给出与两个查询相同的结果。你没有包括“仅联系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;