I am having issues with automapper. I have no clue how to do this and have been searching and trying different solutions. I would appreciate if someone can help me with this.
So here is the issue, I have two source types as shown below:
public class User
{
public string Name {get; set;}
public int Id {get; set;}
}
public class Product
{
public int UserId {get; set;}
public int Id {get; set;}
public double Price{get; set;}
}
I want to map these two to the destination of type UserData:
public class UserData
{
public string UserName{get; set;}
public int UserId {get;set;}
public List<Product> PurchasedProducts {get; set;}
}
Thanks
I got this working using a Custom Value Resolver. But I don't think it is the best solution as the resolver is depending on the repository directly. Anyways here is what I did:
Mapper.CreateMap<Product, Dtos.Product>();
Mapper.CreateMap<User, UserData>()
.ForMember(dest => dest.UserName, opt => opt.MapFrom(src => src.Name))
.ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.PurchasedProducts, opt =>
opt.ResolveUsing<User_Products_Resolver>());
Mapper.AssertConfigurationIsValid();
And I implemented the custom resolver as follows:
public class User_Products_Resolver : ValueResolver<User, List<Product>>
{
protected override List<Product> ResolveCore(User userObj)
{
var productRepo = new ProductRepository();
var r = productRepo.Get(p => p.UserId == userObj.Id)
.ToList<Product>();
return r;
}
}
Again, I am not sure if this is the correct way to do this. If someone knows a better way, please do let me know.
thanks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.