2

给定以下示例类:

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 的扩展方法来扩展 ValueInjector以使用集合,以下将把 's 的集合展平为Order's 的集合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 将 's 集合展平为Order's集合的正确/有效用法LineItem吗?如果没有,还有什么替代方案?(除了不使用 ValueInjector 扩展方法并且只使用一个 for 每个循环将 Header 和 OrderItem 都注入到扁平 LineItem 中)
  2. 使用 AutoMapper 时是否有等价物?
4

0 回答 0