4

I have following data model:

    public class Customer
    {
        [BsonId]
        public int CustomerId { get; set; }
        public string Name { get; set; }
    }

    public class Order
    {
        [BsonId]
        public int OrderId { get; set; }
        [BsonRef("customers")] 
        public Customer Customer { get; set; }
    }

    public class Cart
    {
        [BsonId]
        public int CartID { get; set; }
        public List<Order> OrderList { get; set; }
    }

Now I want to access the customers via queries on my cart collection. I tried something like this:

var collectionCarts = db.GetCollection<Cart>("carts");
var result = collectionCarts.Include("OrderList.Customer").Find(x => x.OrderList[0].Customer.CustomerId == 2);

However, all attempts result in an empty customer object. My database, which I checked with the LiteDB-Viewer seems to be OK.

h0ch5tr4355
  • 2,092
  • 4
  • 28
  • 51

2 Answers2

5

You could get the Customers like this:

using System.Linq;

collectionCarts.SelectMany(c => c.OrderList.Select(o => o.Customer));
Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
0

Are you trying to check only for the first item in the list, or for any item in the list? Because in your query, you are explicitly querying for the first one only.

If not (as I assume), try something like this:

var result = collectionCarts.Include("OrderList.Customer").
                    Find(x => x.Select(v => v.OrderList).Select(v =>v.Customer).
                                     Select(v => v.CustomerId).ToList().Contains(2));
AvrahamL
  • 181
  • 4
  • 16