我需要按标签搜索数据库用户。一个用户有多个标签,一个标签由多个用户共享。但是当我按特定的标签集搜索时,我希望用户拥有所有这些标签,但可以拥有我不搜索ofc的标签。以下是我的尝试:
return context.Contacts.Include("Tags").Where(c => c.Tags.**Any**(t => tagIds.Contains(t.Id.ToString()))).ToList();
//Above approach would search kind of union between tags. It would not converge. Meaning if I have user1 with tags A and B and user2 with B and C And I search by A and B i would get both users, even though i want only user1
//Bellow apporach 会搜索太严格,这意味着如果用户包含标签 A 和 B 并且 i 按标签 A 搜索,则不会显示此用户
return context.Contacts.Include("Tags").Where(c => c.Tags.**All**(t => tagIds.Contains(t.Id.ToString()))).ToList();
您可以使用 LinqKit 包中提供的 PredicateBuilder 类
在包管理器控制台中:
Install-Package LinqKit
然后按如下方式使用 PredicateBuilder:
var predicate = PredicateBuilder.True<Contact>();
foreach (var tagId in tagIds)
{
predicate = predicate.Or(c => c.Tags.Any(tag => tag.Id.ToString() == tagId));
}
var contactsByTags = context.Contacts.Include("Tags").Where(predicate).ToList();