Given the following sample classes:
public class OrderHeader
{
public int OrderHeaderId { get; set; }
public string CustomerName { get; set; }
}
public class OrderItem
{
public int OrderHeaderId { get; set; }
public int OrderItemId { get; set; }
public string ProductName { get; set; }
public float Price { get; set; }
}
// Order contains the header information and a collection of items ordered
public class Order
{
public OrderHeader Header { get; set; }
public IEnumerable<OrderItem> Items { get; set; }
}
// LineItem is OrderHeader and OrderItem flattened out
public class LineItem
{
public int OrderHeaderId { get; set; }
public int OrderItemId { get; set; }
public string CustomerName { get; set; }
public string ProductName { get; set; }
public float Price { get; set; }
}
Using the extension method from jgauffin to extend ValueInjector to work with collections, the following will flatten out a collection of Order
's to a collection of LineItem
's:
var orders = new List<Order>();
var lineItems = new List<LineItem>();
// -extension method for collections with ValueInjector
// -project all the OrderItems into a single list
lineItems.InjectFrom( orders.SelectMany( x => x.Items ) );
// inject the header information into the flattened out LineItem objects
foreach( LineItem item in lineItems )
{
var order = orders.Single( x => x.Header.OrderHeaderId == item.OrderHeaderId );
item.InjectFrom( order.Header );
}
2 questions:
- Is the above pattern a correct/effective usage of using ValueInjector to flatten out a collection of
Order
's to a collection ofLineItem
's? If not, what would be the alternative? (other than not using the ValueInjector extension method and just using a single for each loop to inject both the Header and OrderItem into the flattened LineItem) - Is there an equivalent when using AutoMapper?