我有一个FilterDefinition构建,它将根据非空属性查找地址。
public static FilterDefinition<TU> FindPointByAddress<TU>(Address address)
{
var filterBuilder = Builders<TU>.Filter;
var filterItems = new List<FilterDefinition<TU>>();
if (!String.IsNullOrWhiteSpace(address.Street))
{
filterItems.Add(filterBuilder.Eq("Address.Street", address.Street));
}
if (!String.IsNullOrWhiteSpace(address.City))
{
filterItems.Add(filterBuilder.Eq("Address.City", address.City));
}
if (!String.IsNullOrWhiteSpace(address.StateProvince))
{
filterItems.Add(filterBuilder.Eq("Address.StateProvince", address.StateProvince));
}
if (!String.IsNullOrWhiteSpace(address.PostCode))
{
filterItems.Add(filterBuilder.Eq("Address.PostCode", address.PostCode));
}
return filterBuilder.And(filterItems);
}
IMO这个查询感觉很脏,有没有更好的方法来构建这种类型的查询或者这是正确的方法吗?
答案 0 :(得分:3)
前几天我遇到了类似的情况。我写了一个简单的方法,它将字段名称和字段值作为字符串。
public void AddEqualCompareFilter(string fieldName, string fieldValue)
{
if (String.IsNullOrEmpty(fieldValue) == false) {
if (Filter != null) {
Filter = Filter & Builders<TranslationsDocument>.Filter.Eq(fieldName, fieldValue);
}
else {
FilterCount++;
Filter = Builders<TranslationsDocument>.Filter.Eq(fieldName, fieldValue);
}
}
}
然后我使用此代码段来决定基于FilterCount:
if (FilterCount > 0) {
Result = collection.Find(Filter).ToListAsync().GetAwaiter().GetResult();
return true;
}
else {
Result = collection.Find(new BsonDocument()).ToListAsync().GetAwaiter().GetResult();
return true;
}