I am trying to troubleshoot the following LINQ Query:
public JsonResult SearchNodesByTags(string[] tags)
{
var nodes = _DbContext.Nodes.
Where(n => n.Tags.All(t => tags.Contains(t.DisplayName)))
.Select(n => new {n.NodeNativeId, n.NodeName, n.NodeClass.ClassName})
.ToList();
return Json(nodes);
}
The query is returning a single node that is not associated with a tag. What I want it to do, is return any nodes that have ALL the tags.
The way this is currently constructed, you're only going to end up with the
Node
s where every tag inNode.Tags
has a name in thetags
whitelist, which includesNode
s with no tags.You might want to use the answer from here on subsets:
set1.Except(set2)
contains elements ofset1
that aren't inset2
!set1.Except(set2).Any() == true
ifset2
includes every element ofset1
Edit
It was pointed out in the comments that using Except could generate problematic queries, so I was thinking another option was to get a superset from the database, and further filter the objects within the application:
Edit 2
I just saw another one here that might work for you, but it requires that
Tag.DisplayName
is unique, since it could fail if you have multiple tags with the sameDisplayName
: