Cosmos DB数值字段的字符串搜索实现方法咨询
The core issue here is that your Zip field is a numeric type (like int or long), so you can’t directly call .ToUpper() on it or concatenate it with string values. To include it in your string search, you first need to convert it to a string, while handling any null cases if it’s a nullable numeric type.
Here’s the modified code with the fix integrated:
if (!string.IsNullOrWhiteSpace(filter.Keywords)) { var keywords = filter.Keywords.ToUpper().Split(' '); foreach (var keyword in keywords) query = query.Where(o => (o.Data.General.Dossier.ToUpper() + o.Data.General.OrderId.ToUpper() + (o.Team.Name ?? "").ToUpper() + (o.Data.General.MaintenancePlant ?? "").ToUpper() + (o.Data.Location.BoxNumber ?? "").ToUpper() + (o.Data.Location.City ?? "").ToUpper() + (o.Data.Location.HouseNumber ?? "").ToUpper() + (o.Data.Location.Zip?.ToString() ?? "").ToUpper() // Fixed line: convert numeric Zip to string first + (o.Data.Location.Street ?? "").ToUpper()) .Contains(keyword) ); }
Key Details About the Fix:
o.Data.Location.Zip?.ToString(): Converts the numeric Zip value to a string. The null-conditional operator (?.) prevents null reference exceptions ifZipis a nullable numeric type (likeint?).?? "": IfZipis null, this replaces it with an empty string to avoid breaking the concatenation..ToUpper(): While zip codes are case-insensitive by nature, adding this keeps consistency with your existing search logic (since your keywords are converted to uppercase).
Quick Adjustment for Non-Nullable Zip Fields:
If your Zip is a non-nullable numeric type (like int), you can simplify the line to o.Data.Location.Zip.ToString().ToUpper()—no need for the null check since it can never be null.
Cosmos DB’s LINQ provider will automatically translate this string conversion to the appropriate SQL function (like STRING(Zip)), so the query will execute correctly against your database.
内容的提问来源于stack exchange,提问作者Tom

