Reputation: 68097
I have this chained LINQ query which MongoDB fails to execute:
RoleCollection.AsQueryable().Where(r => r.Users.Any(id => id == user.Id))
.Select(r => r.Name).ToArray();
This results in the following error:
Any is only support for items that serialize into documents. The current serializer is ObjectIdSerializer and must implement IBsonDocumentSerializer for participation in Any queries.
How can I translate the query into a native query which Mongo will support?
Upvotes: 1
Views: 792
Reputation: 68097
I got the following query working, although I'm not entirely certain as to its semantics yet:
RoleCollection.Find(new QueryDocument("Users", user.Id))
.Select(r => r.Name).ToArray();
Upvotes: 1
Reputation: 21989
You should be able to replace .Any()
with a combination of .Where()
and a length check, like so:
RoleCollection.AsQueryable().Where(r => r.Users.Where(id => id == user.Id).Length > 0)
.Select(r => r.Name).ToArray();
Note however that there is a performance implication here since it will pull back all of the Users with that id
to do a length on it.
I'm not sure what Mongo supports (Sorry I'm answering this purely from a linq perspective), but you could also use a combination of FirstOrDefault
and perform a null
check in your where. That might be better since you're only ever expecting one or nothing:
RoleCollection.AsQueryable().Where(r => r.Users.FirstOrDefault(id => id == user.Id) != null)
.Select(r => r.Name).ToArray();
Upvotes: 1