[英]MongoDb C# Driver Issue when trying to filter by enum value
I need some help, I'm new to MongoDb, and using the 2.4.4 MongoDb.Driver for .Net. 我需要一些帮助,我是MongoDb的新手,并且使用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. 我创建了一个用于强烈键入集合的类,并且其中的一个字段是枚举。在添加find时,通过添加BsonRepresentation装饰器,我设法使查询返回的字符串而不是该字段的int。
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 在此先感谢,豪尔赫
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 (ie cannot be parsed by the driver to be converted into a MongoDB query). 一般而言,驱动程序中的LINQ集成不支持任何种类的LINQ语句,以我的经验,在属性上使用
.ToString()
是不支持(即无法被驱动程序解析)的方案之一。转换为MongoDB查询)。
Taking inspiration from https://stackoverflow.com/a/34033905/159446 , you might want to do something like this: 从https://stackoverflow.com/a/34033905/159446汲取灵感,您可能想要执行以下操作:
// 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.