c# - AutoMapper flatten nested collections -
i try figure out how flatten collection of merchants, each containing collection of orders flat list of orderviewmodels.
here dto:
public class merchant { public string merchantname { get; set; } public list<order> orders { get; set; } } public class order { public string orderid { get; set; } }
and here's view model:
public class orderviewmodel { public string merchantname { get; set; } public string orderid { get; set; } }
my goal flatten list<merchant> list<orderviewmodel> whereas following test structure should result in 6 view models:
var mymerchants = new list<merchant> { new merchant { merchantname = "merchant x", orders = new list<order> { new order { orderid = "order 1"}, new order { orderid = "order 2"}, new order { orderid = "order 3"} } }, new merchant { merchantname = "merchant y", orders = new list<order> { new order { orderid = "order 4"}, new order { orderid = "order 5"}, new order { orderid = "order 6"} } } }; var models = mapper.map<list<orderviewmodel>>(mymerchants);
because cardinality of root objects isn't 1:1, (i.e. 2 root merchants
need map 6 orderviewmodels
), may need resort custom typeconverter
, operate @ collection level, can use .selectmany
flattening:
public class mytypeconverter : itypeconverter<ienumerable<merchant>, list<orderviewmodel>> { public list<orderviewmodel> convert(resolutioncontext context) { if (context == null || context.issourcevaluenull) return null; var source = context.sourcevalue ienumerable<merchant>; return source .selectmany(s => s.orders .select(o => new orderviewmodel { merchantname = s.merchantname, orderid = o.orderid })) .tolist(); } }
which can bootstrap:
mapper.createmap<ienumerable<merchant>, list<orderviewmodel>>() .convertusing<mytypeconverter>();
and mapped such:
var models = mapper.map<list<orderviewmodel>>(mymerchants);
Comments
Post a Comment