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

Jorge A.
  • 55
  • 1
  • 8

2 Answers2

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();
Jooeun Lee
  • 331
  • 4
  • 18
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;

spaleet
  • 838
  • 2
  • 10
  • 23
GPuri
  • 495
  • 4
  • 11