使用ValueInjector或AutoMapper展平集合

时间:2012-10-03 00:21:24

标签: c# automapper valueinjecter

给出以下示例类:

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; }
}

使用jgauffin to extend ValueInjector中的扩展方法来处理集合,以下内容将Order的集合展平为LineItem的集合:

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个问题:

  1. 使用ValueInjector将上述模式正确/有效地用于将Order的集合展平为LineItem的集合?如果没有,会有什么替代方案? (除了不使用ValueInjector扩展方法,只使用一个单独的每个循环将Header和OrderItem注入到展平的LineItem中)
  2. 使用AutoMapper时是否有相应的内容?

0 个答案:

没有答案