简体   繁体   English

ASP.NET EF LINQ - 按标签搜索

[英]ASP.NET EF LINQ - Search By Tags

I need to search database users by tags.我需要按标签搜索数据库用户。 One user has many tags and one tag is shared by many users.一个用户有多个标签,一个标签被多个用户共享。 But when I search by specific set of tags I want want users that have all these tags but can have tags that I do not search for ofc.但是当我按特定的标签集搜索时,我希望用户拥有所有这些标签但可以拥有我不搜索 ofc 的标签。 Here were my tries:这是我的尝试:

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 would search too strict, meaning if user contains tags A and B and i search by tag A this user would not be showed //Bellow apporach 会搜索过于严格,这意味着如果用户包含标签 A 和 B 并且我通过标签 A 搜索此用户将不会被显示

 return context.Contacts.Include("Tags").Where(c => c.Tags.**All**(t => tagIds.Contains(t.Id.ToString()))).ToList();

You could use the PredicateBuilder class provided in the LinqKit package您可以使用 LinqKit 包中提供的 PredicateBuilder 类

In your package manager console:在您的包管理器控制台中:

Install-Package LinqKit

And then use the PredicateBuilder as follows:然后使用 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM