Guest User

Untitled

a guest
Oct 18th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. public class Program
  2. {
  3. public static void Main(string[] args)
  4. {
  5. var config = new MapperConfiguration(c =>
  6. {
  7. c.CreateMap<Company, CompanyModel>();
  8. c.CreateMap<Correspondent, CreatorModel>();
  9. });
  10.  
  11. config.AssertConfigurationIsValid();
  12.  
  13. var mapper = config.CreateMapper();
  14. var context = CreateTestContextInstance();
  15. var correspondent = new Correspondent { Company = new Company { Name = "SomeName" } };
  16. context.Correspondents.Add(correspondent);
  17. context.SaveChanges();
  18.  
  19. // That works
  20. var entites = context.Correspondents.ToList();
  21. var models1 = mapper.Map<IList<CreatorModel>>(entites);
  22. // That throws error
  23. var models2 = context.Correspondents.ProjectTo<CreatorModel>(mapper.ConfigurationProvider).ToList();
  24. }
  25.  
  26. public static ApplicationDbContext CreateTestContextInstance()
  27. {
  28. var options = new DbContextOptionsBuilder<ApplicationDbContext>()
  29. .UseInMemoryDatabase(Guid.NewGuid().ToString())
  30. .UseLazyLoadingProxies()
  31. .Options;
  32. var context = new ApplicationDbContext(options);
  33. context.Database.EnsureDeleted();
  34. return context;
  35. }
  36.  
  37.  
  38. public abstract class Entity
  39. {
  40. public Guid Id { get; set; }
  41. }
  42. public class Correspondent : Entity
  43. {
  44. public virtual Company Company { get; set; }
  45. }
  46. public class Company : Entity
  47. {
  48. public string Name { get; set; }
  49. public virtual IList<Correspondent> Correspondents { get; set; } = new List<Correspondent>();
  50. }
  51. public class CreatorModel
  52. {
  53. public string Id { get; set; }
  54. public CompanyModel Company { get; set; }
  55. }
  56. public class CompanyModel
  57. {
  58. public string Id { get; set; }
  59. public string Name { get; set; }
  60. }
  61.  
  62. public class ApplicationDbContext : DbContext
  63. {
  64. public DbSet<Correspondent> Correspondents { get; set; }
  65. public DbSet<Company> Companies { get; set; }
  66. public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
  67. : base(options)
  68. {
  69. }
  70.  
  71. protected override void OnModelCreating(ModelBuilder modelBuilder)
  72. {
  73. base.OnModelCreating(modelBuilder);
  74. }
  75.  
  76. }
  77. }
Add Comment
Please, Sign In to add comment