我似乎遇到了这个问题.我有一个带有 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.
我希望能够通过标签对任务执行 AND 搜索.例如,如果我搜索带有可移植性"和测试"标签的任务,我不想要带有可移植性"而不是测试"标签的任务.
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();
这当然是 OR 搜索,而不是 AND 搜索.我不知道如何将其实际切换为 AND 搜索.
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.
编辑我还需要能够搜索任务包含的 X 个标签中的 2 个.因此,如果任务被标记为错误修复"、可移植性"、测试"并且我搜索测试"和可移植性",该任务仍会显示.
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));
我还没有测试过这个,Distinct 位可能有点差.检查生成的 sql 以确保.
I haven't tested this and the Distinct bit might be off a little. Check the generated sql to be sure.
这篇关于如何在 linq 中检索标有所有提供的标签的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!