using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
public static void Main()
MapperConfiguration _config = new MapperConfiguration(ctx =>
ctx.CreateMap<Product, ProductDto>()
opt => opt.MapFrom((src, dest, member, context) => src.Price - src.Category.CategoryDiscount));
ctx.CreateMap<Category, GetCategoryProductsDto>();
IMapper _mapper = _config.CreateMapper();
var options = new DbContextOptionsBuilder<EntityContext>()
.UseInMemoryDatabase(databaseName: "Add_writes_to_database")
using var context = new EntityContext(options);
List<Category> categories = new List<Category>
new Category { Id = 1, CategoryDiscount = 25 }
context.Categories.AddRange(categories);
List<Product> products = new List<Product>
new Product { Id = 1, CategoryId = 1, Price = 500 },
new Product { Id = 2, CategoryId = 1, Price = 1000 }
context.Products.AddRange(products);
Category category = context.Categories
.Include(x => x.Products)
GetCategoryProductsDto dest = _mapper.Map<GetCategoryProductsDto>(category);
Console.WriteLine(JsonConvert.SerializeObject(dest, Formatting.Indented));
public class EntityContext : DbContext
public EntityContext(DbContextOptions<EntityContext> options) : base(options)
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
Products = new HashSet<Product>();
public int Id { get; set; }
public int CategoryDiscount { get; set; }
public virtual ICollection<Product> Products { get; set; }
public int Id { get; set; }
public int CategoryId { get; set; }
public decimal Price { get; set; }
public virtual Category Category { get; set; } = null!;
public class GetCategoryProductsDto
public int Id { get; set; }
public string CategoryName { get; set; } = string.Empty;
public int CategoryDiscount { get; set; }
public List<ProductDto> Products { get; set; }
public int Id { get; set; }
public int CategoryId { get; set; }
public string ProductName { get; set; }
public int Qty { get; set; }
public decimal Price { get; set; }