2013-03-03 2 views
8

Я пытаюсь запросить свои коллекции, но я не уверен, как это сделать «добавить» своего рода в Query.And()Как использовать запрос MongoDB и QueryBuilder в C# foreach?

Вот моя модель предметной области для создания 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") 
); 

ответ

7

Хотя непроверенные (как у меня нет сценария, подобных вашей, чтобы проверить с), вы должны быть в состоянии просто добавить различные and условия сборник (который реализует IEnumerable), как это, а затем передать его в And способе QueryBuilder например:

var andList = new List<IMongoQuery>(); 

foreach (var attribute in item.Attributes) 
{ 
    andList.Add(Query.EQ("Attributes.AttributeName", attribute.AttributeName)); 
    andList.Add(Query.EQ("Attributes.AttributeValue", attribute.AttributeValue)); 
} 

andList.Add(Query.EQ("TemplateId", item.TemplateId)); 
andList.Add(Query.NE("UsernameOwner", item.UsernameOwner)); 

var query = new QueryBuilder<Item>(); 
query.And(andList); 
// do something with query ... 

Приведенный выше код должен быть эквивалентен выполнения $and на всех указанных условиях.

+0

Остерегайтесь элементов массива и смотрите на элементы наблюдения за элементами массива и посмотрите http://docs.mongodb.org/manual/reference/projection/elemMatch/. использование 2 "и" терминов в массиве не означает, что имя attr и значение attr происходят внутри одного и того же элемента. –

Смежные вопросы