Nick Reeve
Nick Reeve

Reputation: 1680

Entity Framework Contains method and objects

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

Upvotes: 1

Views: 4822

Answers (2)

Krunal
Krunal

Reputation: 3541

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()

Upvotes: 3

Craig Stuntz
Craig Stuntz

Reputation: 126587

var orders = db.Orders.Where(m => m.OrderItems.Any(i => i.OrderId == 5)).ToList();

Upvotes: 5

Related Questions