我如何检索标记有在LINQ提供的所有标签的​​项目? [英] How do I retrieve items that are tagged with all the supplied tags in linq?

查看:235
本文介绍了我如何检索标记有在LINQ提供的所有标签的​​项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎有这个麻烦。我有一个ID和一个标签表中,有一个标签字段和外键约束任务表任务表。

I seem to be having trouble with this. I have a Task table with an ID, and a Tag table, that has a tag field and a foreign key constraint to the task table.

我希望能够通过标签为执行任务并搜索。因此,例如,如果我搜索与标签便携性的任务和测试,我不想被标签为便携性,而不是测试的任务。

I want to be able to perform AND searches for tasks by tags. So for example, if I search for tasks with the tags "portability" and "testing", I don't want tasks that are tagged with "portability" and not "testing".

我试过的语法如下:

 var tasks = (from t in _context.KnowledgeBaseTasks
                     where t.KnowledgeBaseTaskTags.Any(x => tags.Contains(x.tag))
                     select KnowledgeBaseTaskViewModel.ConvertFromEntity(t)
                    ).ToList();



当然,这一个或搜索,而不是和搜索。我无法弄清楚如何真正切换这是一个与搜索。

This of course does an OR search, not an AND search. I can't figure out how to actually switch this to be an AND search.

修改
我还需要能够搜索2出一个任务包含点¯x标签。因此,如果任务标记为漏洞修复,便携,测试,我搜索测试和便携性,该任务仍然会显示出来。

Edit I also need to be able to search for 2 out of X tags that a task contains. So if the task is tagged with "bugfix", "portability", "testing" and I search for "testing" and "portability", that task will still show up.

推荐答案

您想要做的这个

LinqToSql可能是这样的:

the LinqToSql might look like:

List<int> myTags = GetTagIds();
int tagCount = myTags.Count;

IQueryable<int> subquery =
  from tag in myDC.Tags
  where myTags.Contains(tag.TagId)
  group tag.TagId by tag.ContentId into g
  where g.Distinct().Count() == tagCount
  select g.Key;

IQueryable<Content> query = myDC.Contents
  .Where(c => subQuery.Contains(c.ContentId));



我没有测试过这和鲜明位可能为关闭一点点。检查生成的sql是肯定的。

I haven't tested this and the Distinct bit might be off a little. Check the generated sql to be sure.

这篇关于我如何检索标记有在LINQ提供的所有标签的​​项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆