問題描述
我似乎遇到了這個問題.我有一個帶有 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 中檢索標有所有提供的標簽的項目?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!