2

I need some help, I'm new to MongoDb, and using the 2.4.4 MongoDb.Driver for .Net.

I've created a class to strongly type my collection and one of its fields is an enum, I've managed to make the query return a string instead of an int on that field when using find by adding a BsonRepresentation decorator.

My current issue is when trying to filter by that enum field, I'm trying to do the following:

return await _context.Contacts
    .Find(x=> x.EnumField.ToString().Contains(searchTextParam)).ToListAsync();

So that I can filter by that field's text value, but that's throwing a runtime error:

System.ArgumentException: Unsupported filter: {document}{EnumField}.ToString().Contains("searchValue").

Thanks in advance, Jorge

1
  • I have exactly the same problem, I'm curious did you solve this problem? Thanks Commented Dec 3, 2018 at 5:33

2 Answers 2

0

Generally speaking, the LINQ integration in the driver does not support any and every kind of LINQ statement, and in my experience, using .ToString() on a property is one of those scenarios that is not supported (i.e. cannot be parsed by the driver to be converted into a MongoDB query).

Taking inspiration from https://stackoverflow.com/a/34033905/159446, you might want to do something like this:

// assuming your class is also called Contacts
var filter = Builders<Contacts>.Filter.Regex(x => x.EnumField, 
              BsonRegularExpression.Create(searchTextParam));
return await _context.Contacts
     .Find(filter).ToListAsync();
Sign up to request clarification or add additional context in comments.

Comments

0

Augmenting the other answer, we can use FilterDefinitions with queryable using Inject() method. So just use regex filter on enum using builder and then inject it inside where linq method and we have queryable which will form a correct query. In sample code below _.EnumType is the enum

var searchText = "SomeValue".ToLower();

var confidentialityFilter = Builders<MyType>.Filter.Regex(_ => 
    _.EnumType, @$ "/{searchText}/is");
    
query = query.Where(_ => 
    _.SomeTextField
    .ToLower()
    .Contains(searchText) || confidentialityFilter.Inject());
    
return query;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.