Reputation: 553
How can I convert IEnumerable<Category>
to IEnumerable<CategoryViewModel>
with this definition
public class Category
{
public Guid Id { get; set; }
public string Name { get; set; }
public DateTime CreationTime { get; set; }
}
public class CategoryViewModel
{
public Guid CategoryId { get; set; }
public string Name { get; set; }
}
I have done like this
public static IEnumerable<CategoryViewModel> ConvertToCategoryViewModelList(this IEnumerable<Category> category)
{
return Mapper.Map<IEnumerable<Category>, IEnumerable<CategoryViewModel>>(category);
but it doesn't map Id to CategoryId and also I don't want to have CreationTime in CategoryVeiwModel
Upvotes: 0
Views: 678
Reputation: 14318
Either property names should match, or you have to override the mapping for the Id
. Also you have to explicitly Ignore
the CreationTime
:
AutoMapper.Mapper.CreateMap<Category, CategoryViewModel>()
.ForMember(x => x.CategoryId, src => src.MapFrom(y => y.Id))
.ForSourceMember(x => x.CreationTime, y => y.Ignore());
Upvotes: 1
Reputation: 2112
I think you can use inheritance and down cast (or is it up casting)
public class Category : CategoryViewModel
{
public DateTime CreationTime { get; set; }
}
public class CategoryViewModel
{
public Guid CategoryId { get; set; }
public string Name { get; set; }
}
Upvotes: 0