是否可以使用自动映射器对资源中的数据进行分组?
例如:
public class Order
{
public Guid ID{ get; set; }
public ICollection<OrderLine> OrderLines { get; set; }
}
public class OrderLine
{
public Guid OrderID { get; set; }
public Order Order { get; set; }
public Guid ProductID { get; set; }
public Product Product { get; set; }
public int Year { get; set }
}
public class Product
{
public Guid ID{ get; set; }
public ICollection<OrderLine> OrderLines { get; set; }
}
public class OrderResource
{
public Guid ID { get; set; }
public ICollection<YearResource> Years { get; set; }
public OrderResource()
{
Years = new Collection<YearResource>();
}
}
public class YearResource
{
public int Year { get; set; }
public ICollection<Guid> ProductIds { get; set; }
}
例如,我希望基于年份对productId进行分组:
{
id: "random-id-tst",
years: [
{
year: 1,
productIds: ['guid-id-1', 'guid-id-2'],
},
]
}
我正在努力使其与Years分组。所以现在我明白了:
{
id: "random-id-tst",
years: [
{
year: 1,
productIds: ['guid-id-1'],
},
{
year: 1,
productIds: ['guid-id-2'],
},
]
}
我尝试使用groupBy,但我认为automapper不支持它,并且无法使其正常工作。
cfg.CreateMap<Order, OrderResource>().ForMember(dest => dest.Years, opt => opt.MapFrom(src => src.OrderLines.Select(ol => ol.Product).ToList()))
// tried grouping on OrderLines but that's not working
cfg.CreateMap<Product, YearResource>().ForMember(dest => dest.Year, opt => opt.MapFrom(src => src.OrderLines.Select(e => e.Year).First()));
您需要使用LINQ的GroupBy。这是有关GroupBy用法的示例,此示例提供了根据Cars的名称对它们进行分组的方法,
List<Car> cars = new List<Car>();
cars.Add(new Car() { Name = "Renault", Price = 250 });
cars.Add(new Car() { Name = "BMW", Price = 700 });
cars.Add(new Car() { Name = "Renault", Price = 150 });
cars.Add(new Car() { Name = "Renault", Price = 250 });
cars.Add(new Car() { Name = "Renault", Price = 100 });
List<Car> result = cars.GroupBy(x => x.Name).Select(x => new Car() { Name = x.Key, Price = x.Sum(y=>y.Price) }).ToList();
//to print output
result.ForEach(x => Console.WriteLine(string.Concat("Name: ", x.Name, " Total Price: ", x.Price)));
Console.ReadKey();
和汽车模型,
public class Car {
public string Name { get; set; }
public int Price { get; set; }
}