views:

33

answers:

2

Hi,

Is there a way of using the Contains method in Entity Framework 4 with the actual id of the object?

Take these entities as an example:

public class Order
{
  public int OrderId { get; set; }              // PK
  public string CustomerId { get; set; }        // FK to Customer
}

public class OrderItem
{
  public int OrderId { get; set; }              // PK
  public int ItemId { get; set; }               // PK, FK to Item
}

public class Item
{
  public int ItemId { get; set; }               // PK
  public string ItemName { get; set; }
}

and I want to return a list of all orders that have item '5' in them.

I want to be able to do:

List<Order> orders = db.Orders.Where(m => m.OrderItems.Contains(5)).ToList()

But that won't work because Contains needs an actual OrderItem object.

Thanks

+3  A: 

Try this:

List<Order> orders = db.Orders.Where(m => m.OrderItems.Any(i=>i.OrderId==5)).ToList()

OR

List<Order> orders = db.OrderItems.Where(m => m.OrderId==5).Orders.ToList()
Krunal
`Contains` doesn't take an expression.
Craig Stuntz
@Craig - + 1. Thanks, I thought it is supported. Corrected answer.
Krunal
+1  A: 
var orders = db.Orders.Where(m => m.OrderItems.Any(i => i.OrderId == 5)).ToList();
Craig Stuntz
Simple as that. Thanks very much
Nick Reeve