Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework - select by multiple conditions in same column - Many to Many

I asked very similar question here
Entity framework - select by multiple conditions in same column - referenced table

Now relationship is Many to Many. So I have 3 tables: order, items and orderItem (items is a Junction table) Again.. I want to select all orders that have at least one orderItem with price 100 and at least one orderItem with price 200

I really don't know how to edit this for that scenario.

var orders = from o in kontextdbs.orders
             select o;
foreach(int value in values)
{    
      int tmpValue = value;
      orders = orders.Where(x => kontextdbs.order_item.Where(oi => x.id == oi.order_id)
} 
like image 833
quin16 Avatar asked Nov 04 '22 01:11

quin16


2 Answers

Here is the modified version

foreach(int value in values)
{    
      int tmpValue = value;
      orders = orders.Where(x => (from oi in kontextdbs.order_item
                                 join i in kontextdbs.items on oi.item_id equals i.id
                                 where x.id == oi.order_id
                                 select i).Any(y => y.price == tmpValue));    
}
like image 150
Aducci Avatar answered Nov 09 '22 06:11

Aducci


First, you can just declare this:

var orders = kontextdbs.orders;

There's no need to use an actual select statement.

To answer your actual question, you should be able to do this:

foreach(int value in values)
{
    var temp = value;

    orders = orders.Where(o => o.order_item.Any(oi => oi.price == temp));
}

This assumes that you have a navigation property from order to order_item.

like image 45
Adam Robinson Avatar answered Nov 09 '22 06:11

Adam Robinson