Search code examples
c#entity-frameworklinqasp.net-core

Entity Framework C# join with one column only from second table


I have a join in Entity Framework connecting the Order and the OrderItem tables. All orders will have multiple order items. I'm trying to return all the orders, but only the orderItemStatus column from the OrderItem list.

In my Order model class, I have this property:

public List<int>? orderItemStatus { get; set; }

I'm joining the 2 tables ok, but it's returning all columns from the OrderItem.

orderList = await _context.Order
                          .Include(orderItem => orderItem)
                          .ToListAsync();

How do I get a list of the orders with just the OrderItem.orderItemStatus values?

Order Table

Order Table

OrderItem Table

OrderItem Table

Required Results - the OrderItemStatus column can be a List<> or comma delimited

Required Results


Solution

  • Managed to get it working with GroupJoin

     result = await _context.Order
            .GroupJoin(_context.OrderItem,
            order => order.OrderID,
            orderItem => orderItem.OrderID,
            (Order, OrderItemStatus) => new OrderIndex
            {
                OrderID = Order.OrderID,
                //other Order properties here
                OrderItemStatus = OrderItemStatus.Select(x => x.OrderItemStatus).ToList(),
            }).ToListAsync();