Sisyphus
Sisyphus

Reputation: 910

Relation from master to details but not vice versa

I have a Order entity that has multiple OrderItem entities. and classes would look like that.

class Order
{
     int Id;
     string Note;
     List<OrderItem> OrderItems;
}

class OrderItem
{
     int Id;
     string Name;
}

as you can see, Order knows about its OrderItems and OrderItem doesn't know about its Order.

The question is how do I write a linq query to query the context for an OrderItem that belongs to a specific order?

Upvotes: 1

Views: 48

Answers (3)

Salah Akbari
Salah Akbari

Reputation: 39966

You need an Order property in your OrderItem class. Also you should use properties in your classes instead of fields like below:

public class Order
{
    public int Id { get; set; }
    public string Note { get; set; }
    public virtual ICollection<OrderItem> OrderItems { get; set; }
}

public class OrderItem
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Order Order { get; set; }
}

Also note that I used the virtual keyword and ICollection instead of List which makes the property supports lazy loading.

Upvotes: 2

Peter Morris
Peter Morris

Reputation: 23244

Context.Orders.Where(x => x.Id == 1234).SelectMany(x => x.OrderItems);

or you could do Context.Where(x => x.Id == 1234).Include(x => x.OrderItems) to get the order and pre-load its items.

I recommend making the Order.OrderItems property virtual, so at least if ever you forget to pre-load (or .Include) then you won't get inconsistent data loaded from the DB.

Upvotes: 2

M4N
M4N

Reputation: 96596

You would query for the correct Order, then select the related OrderItem(s), e.g:

var orderItems = context.Orders
                        .Where(o => o.Id == selectedId)
                        .Select(o => o.OrderItems)
                        .ToList();

This gives you the list of order items associated to the order with Id selectedId.

Upvotes: 2

Related Questions