问题
I have a docuemnt like this:
public class Order
{
public string ClientName { get; set; }
public List<OrderItem> Items { get; set; }
}
public class OrderItem
{
public string ProductCode { get; set; }
public int Quantity { get; set; }
}
And I need to query collection of theese documents like this:
var q = session.Query<Order_Index.Result, Order_Index>()
.Where(o => o.ClientName.StartsWith("Jho") &&
o.Items.Any(i => i.ProductCode == "Book" && i.Quantity >= 10))
.OfType<Order>();
Every example of indexing and querying hierarhical data, that I found, shows only case, when only one property of complex nested object is used in separate query expression. e.g.:
var q = session.Query<Order_Index.Result, Order_Index>()
.Where(o => o.ClientName.StartsWith("Jho") &&
o.ItemProductCodes.Any(c => c == "Book") &&
o.ItemQuantities.Any(qty => qty >= 10))
but none of them consider my situation.
I tried to index ProductCode and Quantity as separate collections and then join them by collection index while querying, but this throws some kind of Linq translation exception. I wonder, is there any opportunity to do this kind of querying in RavenDB?
回答1:
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Order> session = new List<Order>() {
new Order() { ClientName = "Jho", Items = new List<OrderItem>() {
new OrderItem() { ProductCode = "abc", Quantity = 1},
new OrderItem() { ProductCode = "def", Quantity = 4},
new OrderItem() { ProductCode = "Book", Quantity = 5},
new OrderItem() { ProductCode = "jkl", Quantity = 10}
}
},
new Order() { ClientName = "Mary", Items = new List<OrderItem>() {
new OrderItem() { ProductCode = "mno", Quantity = 2},
new OrderItem() { ProductCode = "pqr", Quantity = 3},
new OrderItem() { ProductCode = "stu", Quantity = 4},
new OrderItem() { ProductCode = "vwx", Quantity = 5}
}
},
new Order() { ClientName = "Jho", Items = new List<OrderItem>() {
new OrderItem() { ProductCode = "abc", Quantity = 28},
new OrderItem() { ProductCode = "cdf", Quantity = 7},
new OrderItem() { ProductCode = "Book", Quantity = 26},
new OrderItem() { ProductCode = "jkl", Quantity = 5}
}
}
};
var q = session.Where(o => o.ClientName.StartsWith("Jho") && o.Items.Where(i => i.ProductCode == "Book" && i.Quantity >= 10).Any()).ToList();
}
}
public class Order
{
public string ClientName { get; set; }
public List<OrderItem> Items { get; set; }
}
public class OrderItem
{
public string ProductCode { get; set; }
public int Quantity { get; set; }
}
}
来源:https://stackoverflow.com/questions/42030294/ravendb-indexing-and-querying-complex-hierarhical-data-nested-properties