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
Database 多行的Linq查询条件_Database_Linq_Linq To Entities - Fatal编程技术网

Database 多行的Linq查询条件

Database 多行的Linq查询条件,database,linq,linq-to-entities,Database,Linq,Linq To Entities,我试图解决过去两天的一个问题,但没有解决。 它看起来容易理解,但无法制作 例如,表中有两列: ResourceId || MappingId 1 2 1 3 2 2 2 4 3 2 3 4 4 2 4 5 5

我试图解决过去两天的一个问题,但没有解决。 它看起来容易理解,但无法制作

例如,表中有两列:

ResourceId  ||   MappingId

      1            2
      1            3
      2            2
      2            4
      3            2
      3            4
      4            2
      4            5
      5            2
      5            4
这是一个包含两个字段ResourceId和MappingId的表。 现在我想要一个resourceId,它有Mappingid{2,4}

表示答案必须是ResourceId{2,3,5}


如何在Linq查询中获得此答案?

使用集合的
包含
。此方法可通过实体框架在运算符中转换为SQL:

int[] mappingIds = { 2, 4 };
var resources = from t in table
                where mappingIds.Contains(t.MappingId)
                select t.ResourceId;
Lambda语法:

var  resources = table.Where(t => mappingIds.Contains(t.MappingId))
                      .Select(t => t.ResourceId);
生成的SQL将如下所示:

SELECT [Extent1].[ResourceId]
FROM [dbo].[TableName] AS [Extent1]
WHERE [Extent1].[MappingId] IN (2,4)

更新:如果您想要获取所有提供了映射ID的资源,那么

var resources = from t in table
                group t by t.ResourceId into g
                where mappingIds.All(id => g.Any(t => t.Id == id))
                select g.Key;
实体框架能够将此查询转换为SQL,但它不会像上面的查询那样漂亮。

IQueryable resourceIds=table
IQueryable<int> resourceIds = table
     // groups items by ResourceId
     .GroupBy(item => item.ResourceId)
     // consider only group where: an item has 2 as MappingId value
     .Where(group => group.Select(item => item.MappingId).Contains(2))
     // AND where: an item has 4 as MappingId value
     .Where(group => group.Select(item => item.MappingId).Contains(4))
     // select Key (= ResourceId) of filtered groups
     .Select(group => group.Key);
//按资源ID对项目进行分组 .GroupBy(item=>item.ResourceId) //只考虑组:其中项具有2作为MAPPIGID值 .Where(group=>group.Select(item=>item.MappingId).Contains(2)) //其中:一个项的MappingId值为4 .Where(group=>group.Select(item=>item.MappingId).Contains(4)) //选择筛选组的键(=资源ID) .Select(group=>group.Key);
谢谢Sergey。。但如果我使用Contains而不是get资源,则映射id为2或其id为4。。并非两者都有…@user3410950它将为您提供具有任何提供的映射ID的所有行,但我需要resourceid,它必须具有两个映射ID{2,4}。。在您的案例中,ResourceId要么是MappingId有2个,要么是它有4个意思或条件