I have the following two ShopifySharp
objects.
public class Product
{
public string Title { get; set; }
public string BodyHtml { get; set; }
public IEnumerable<ProductVariant> Variants { get; set; }
}
public class ProductVariant
{
public string Title { get; set; }
public string Barcode { get; set; }
}
I then have the following model
public class ShopifyVariant
{
public long Id { get; set; }
public long ProductId { get; set; }
public string ProductName { get; set; }
public string VariantName { get; set; }
public string Price { get; set; }
}
I want to map an instance of ShopifySharp.Product
to IEnumerable<ShopifyVariant>
because each ShopifySharp.Product
will always have have AT LEAST a single ProductVariant
.
Usually this would be a trivial problem because you could simply create a map between the two objects along the lines of:
this.CreateMap<ShopifySharp.ProductVariant, ShopifyVariant>()
BUT I need to get the ProductName and ProductId for each variant which can only be obtained from the ShopifySharp.Product
object.
My initial thought was to try something like this
this.CreateMap<ShopifySharp.ProductVariant, ShopifyVariant>()
.ForMember(o => o.Id, o => o.MapFrom(f => f.Id))
.ForMember(o => o.ProductId, o => o.MapFrom((src, dest, m, c) => c.Items["ProductId"]))
.ForMember(o => o.ProductName, o => o.MapFrom((src, dest, m, c) => c.Items["ProductName"]))
.ForMember(o => o.VariantName, o => o.MapFrom(f => f.Title));
this.CreateMap<ShopifySharp.Product, IEnumerable<ShopifyVariant>>()
But it was unclear to me how to actually create the projection from Product to IEnumerable.
I’m currently playing with using a Custom ITypeConverter
but haven’t worked it out yet.
Can anyone help? How do you map a single instance of an object to a collection of reduced entities?
2
Answers
I have solved the problem (suboptimally) using the following mappings.
Would love to see a better approach.
As I’ve already said in the comments, some LINQ would help a lot here. But here it is. You can apply the same idea to your version. Most of the
MapFrom
s you have are useless.The
IEnumerable
map can be omitted and replaced with the same code inline, when callingMap
.