Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using AutoMapper;
- using System;
- using System.Collections.Generic;
- namespace TestAutoMapperInheritanceMapping
- {
- public class Program
- {
- public static void Main(string[] args)
- {
- Mapper.Initialize(cfg =>
- {
- cfg.CreateMap(typeof(IEnumerable<>), typeof(CollectionDto<>))
- .ForMember("Records", opt => opt.MapFrom(src => src));
- cfg.CreateMap<SomeObject, SomeObjectDto>();
- });
- var list = new List<SomeObject>
- {
- new SomeObject { Property1 = 1, Property2 = 2 },
- new SomeObject { Property1 = 3, Property2 = 4 },
- };
- var result = Mapper.Map<SomeObjectCollectionDto>(list);
- foreach (var x in result.Records)
- {
- Console.WriteLine(x);
- }
- Console.ReadKey();
- }
- }
- public class CollectionDto<T>
- where T : class
- {
- public int Count => Records.Count;
- public ICollection<T> Records { get; set; }
- }
- // Some custom attributes here that only apply to
- // SomeObjectDto things.
- public class SomeObjectCollectionDto : CollectionDto<SomeObjectDto>
- { }
- public class SomeObject
- {
- public int Property1 { get; set; }
- public int Property2 { get; set; }
- }
- public class SomeObjectDto
- {
- public int Property1 { get; set; }
- public int Property2 { get; set; }
- public override string ToString()
- {
- return $"Property1: {Property1} | Property2: {Property2}";
- }
- }
- }
Add Comment
Please, Sign In to add comment