Skip to content

Instantly share code, notes, and snippets.

@lbargaoanu
Last active February 9, 2024 06:05
Show Gist options
  • Save lbargaoanu/0cbc531306223f7ffc5468becf2642d6 to your computer and use it in GitHub Desktop.
Save lbargaoanu/0cbc531306223f7ffc5468becf2642d6 to your computer and use it in GitHub Desktop.
public void Main()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateProjection<Product, ProductArticle>()
.ForMember(d => d.Price, o => o.MapFrom(source => source.Articles.Where(x => x.IsDefault && x.NationId == 1 && source.ECommercePublished).FirstOrDefault()));
cfg.CreateProjection<ProductArticle, ProductModel>();
cfg.CreateProjection<Article, PriceModel>()
.ForMember(d => d.RegionId, o => o.MapFrom(s => s.NationId));
});
config.AssertConfigurationIsValid();
var mapper = config.CreateMapper();
var context = new ClientContext();
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
context.Products.Add(new UserQuery.Product {ECommercePublished=true, Articles = new []{ new Article{IsDefault=true, NationId=1, ProductId=1}}});
context.SaveChanges();
var result = mapper.ProjectTo<ProductArticle>(context.Products);//.Dump();
}
public partial class ProductArticle
{
public int Id { get; set; }
public string Name { get; set; }
public bool ECommercePublished { get; set; }
public virtual ICollection<Article> Articles { get; set; }
public Article Price;
}
public partial class Article
{
public int Id { get; set; }
public int ProductId { get; set; }
public bool IsDefault { get; set; }
public short NationId { get; set; }
public virtual Product Product { get; set; }
}
public partial class Product
{
public int Id { get; set; }
public string Name { get; set; }
public bool ECommercePublished { get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
public class PriceModel
{
public int Id { get; set; }
public short RegionId { get; set; }
public bool IsDefault { get; set; }
}
public class ProductModel
{
public int Id { get; set; }
public PriceModel Price { get; set; }
}
class ClientContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseSqlServer(
@$"Data Source=(localdb)\mssqllocaldb;Integrated Security=True;MultipleActiveResultSets=True;Database={GetType()};Connection Timeout=300",
o => o.EnableRetryOnFailure(maxRetryCount: 10).CommandTimeout(120));
public DbSet<Product> Products { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment