Guest User

Untitled

a guest
Mar 17th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. using AutoMapper;
  2. using System;
  3. using System.Collections.Generic;
  4.  
  5. namespace TestAutoMapperInheritanceMapping
  6. {
  7. public class Program
  8. {
  9. public static void Main(string[] args)
  10. {
  11. Mapper.Initialize(cfg =>
  12. {
  13. cfg.CreateMap(typeof(IEnumerable<>), typeof(CollectionDto<>))
  14. .ForMember("Records", opt => opt.MapFrom(src => src));
  15. cfg.CreateMap<SomeObject, SomeObjectDto>();
  16. });
  17.  
  18. var list = new List<SomeObject>
  19. {
  20. new SomeObject { Property1 = 1, Property2 = 2 },
  21. new SomeObject { Property1 = 3, Property2 = 4 },
  22. };
  23.  
  24. var result = Mapper.Map<SomeObjectCollectionDto>(list);
  25.  
  26. foreach (var x in result.Records)
  27. {
  28. Console.WriteLine(x);
  29. }
  30.  
  31. Console.ReadKey();
  32. }
  33. }
  34.  
  35. public class CollectionDto<T>
  36. where T : class
  37. {
  38. public int Count => Records.Count;
  39. public ICollection<T> Records { get; set; }
  40. }
  41.  
  42. // Some custom attributes here that only apply to
  43. // SomeObjectDto things.
  44. public class SomeObjectCollectionDto : CollectionDto<SomeObjectDto>
  45. { }
  46.  
  47. public class SomeObject
  48. {
  49. public int Property1 { get; set; }
  50. public int Property2 { get; set; }
  51. }
  52. public class SomeObjectDto
  53. {
  54. public int Property1 { get; set; }
  55. public int Property2 { get; set; }
  56.  
  57. public override string ToString()
  58. {
  59. return $"Property1: {Property1} | Property2: {Property2}";
  60. }
  61. }
  62. }
Add Comment
Please, Sign In to add comment