2

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:

  1. Is the above pattern a correct/effective usage of using ValueInjector to flatten out a collection of Order's to a collection of LineItem'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)
  2. Is there an equivalent when using AutoMapper?
Community
  • 1
  • 1
Metro Smurf
  • 37,266
  • 20
  • 108
  • 140
  • @ChuckNorris - IIRC, you are one of the authors of ValueInjecter? If so, feel free to post an answer and I'll accept. – Metro Smurf Oct 03 '12 at 22:52
  • @ChuckNorris If you don't mind could you answer this http://stackoverflow.com/questions/12777676/steps-to-map-classes-using-valueinjector – Deeptechtons Oct 08 '12 at 08:52

0 Answers0