Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Program
- {
- public static void Main(string[] args)
- {
- var config = new MapperConfiguration(c =>
- {
- c.CreateMap<Company, CompanyModel>();
- c.CreateMap<Correspondent, CreatorModel>();
- });
- config.AssertConfigurationIsValid();
- var mapper = config.CreateMapper();
- var context = CreateTestContextInstance();
- var correspondent = new Correspondent { Company = new Company { Name = "SomeName" } };
- context.Correspondents.Add(correspondent);
- context.SaveChanges();
- // That works
- var entites = context.Correspondents.ToList();
- var models1 = mapper.Map<IList<CreatorModel>>(entites);
- // That throws error
- var models2 = context.Correspondents.ProjectTo<CreatorModel>(mapper.ConfigurationProvider).ToList();
- }
- public static ApplicationDbContext CreateTestContextInstance()
- {
- var options = new DbContextOptionsBuilder<ApplicationDbContext>()
- .UseInMemoryDatabase(Guid.NewGuid().ToString())
- .UseLazyLoadingProxies()
- .Options;
- var context = new ApplicationDbContext(options);
- context.Database.EnsureDeleted();
- return context;
- }
- public abstract class Entity
- {
- public Guid Id { get; set; }
- }
- public class Correspondent : Entity
- {
- public virtual Company Company { get; set; }
- }
- public class Company : Entity
- {
- public string Name { get; set; }
- public virtual IList<Correspondent> Correspondents { get; set; } = new List<Correspondent>();
- }
- public class CreatorModel
- {
- public string Id { get; set; }
- public CompanyModel Company { get; set; }
- }
- public class CompanyModel
- {
- public string Id { get; set; }
- public string Name { get; set; }
- }
- public class ApplicationDbContext : DbContext
- {
- public DbSet<Correspondent> Correspondents { get; set; }
- public DbSet<Company> Companies { get; set; }
- public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
- : base(options)
- {
- }
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- base.OnModelCreating(modelBuilder);
- }
- }
- }
Add Comment
Please, Sign In to add comment