我正在尝试查询我的收藏,但我不确定如何“追加”各种Query.And()
这是我创建Item
文档的域模型:
public class Item
{
public ObjectId Id { get; set; }
public string ItemTypeTemplate { get; set; }
public string UsernameOwner { get; set; }
public IList<ItemAttribute> Attributes { get; set; }
}
IList<ItemAttribute>
集合根据ItemTypeTemplate
(项目属性的预定列表的某种查找键)而变化
这是一个Item
文档示例:
{
"_id" : ObjectId("5130f9a677e23b11503fee72"),
"ItemTypeTemplate" : "Tablet Screens",
//can be other types like "Batteries", etc.
//which would change the attributes list and values
"UsernameOwner" : "user032186511",
"Attributes" : [{
"AttributeName" : "Screen Size",
"AttributeValue" : "10.1"
}, {
"AttributeName" : "Pixel Density",
"AttributeValue" : "340"
}]
}
问题
鉴于 的“动态”性质IList<ItemAttribute>
,我无法手动指定额外的查询条件AttributeName
,AttributeValue
因此我想到了使用循环来构建查询:
QueryBuilder<Item> qbAttributes = new QueryBuilder<Item>();
foreach (var attribute in item.Attributes)
{
qbAttributes.And(
Query.EQ("Attributes.AttributeName", attribute.AttributeName),
Query.EQ("Attributes.AttributeValue", attribute.AttributeValue),
);
}
var query = Query.And(
Query.EQ("TemplateId", item.TemplateId),
Query.NE("UsernameOwner", item.UsernameOwner)
);
return DBContext.GetCollection<Item>("Items").Find(query).AsQueryable();
我如何“附加”qbAttributes
到query
?我尝试过qbAttributes.And(query);
,但.Find(query)
由于参数无效而出错。
我需要这样的东西:
var query = Query.And(
Query.EQ("ItemTypeTemplate", item.ItemTypeTemplate), //Tablet Screens
Query.NE("UsernameOwner", item.UsernameOwner) //current user
// this part is generated by the loop
Query.EQ("Attributes.AttributeName", "Screen Size"),
Query.EQ("Attributes.AttributeValue", "10.1"),
Query.EQ("Attributes.AttributeName", "Pixel Density"),
Query.EQ("Attributes.AttributeValue", "340")
);