Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //mapping
- CreateMap<Sale, ExportSaleDto>()
- .ForMember(cfg => cfg.Discount, opt => opt.MapFrom(x => Math.Round(x.Discount,2)))
- .ForMember(cfg => cfg.CustomerName, opt => opt.MapFrom(x => x.Customer.Name))
- .ForMember(cfg=>cfg.ExportFerariCars,opt=>opt.MapFrom(x=>x.Car))
- .ForMember(cfg => cfg.Price,
- opt => opt.MapFrom(x => Math.Round(x.Car.Parts.Sum(p => p.Part.Price),2)));
- //dtos
- [XmlType("sale")]
- public class ExportSaleDto
- {
- [XmlIgnore]
- public decimal Pricewithdiscount;
- [XmlElement("car")]
- public ExportFerariCars ExportFerariCars { get; set; }
- [XmlElement("customer-name")]
- public string CustomerName { get; set; }
- [XmlElement("discount")]
- public double Discount { get; set; }
- [XmlElement("price")]
- public decimal Price { get; set; }
- // i needed to make PriceWithDiscount this way or xmlserializer couldn't see it
- // strange but true and it worked
- [XmlElement("price-with-discount")]
- public decimal PriceWithDiscount
- {
- get => Math.Round(this.Price -= this.Price * (decimal)this.Discount, 2);
- set => Pricewithdiscount = value;
- }
- }
- ............
- public class ExportFerariCars
- {
- [XmlAttribute("make")]
- public string Make { get; set; }
- [XmlAttribute("model")]
- public string Model { get; set; }
- [XmlAttribute("travelled-distance")]
- public long Distance { get; set; }
- }
- //method for the query:
- public static void SalesWithAppliedDiscount(IMapper mapper, CarDealerContext context)
- {
- var sales = context.Sales.ProjectTo<ExportSaleDto>(mapper.ConfigurationProvider).ToArray();
- StringBuilder sb = new StringBuilder();
- var serializer = new XmlSerializer(typeof(ExportSaleDto[]), new XmlRootAttribute("sales"));
- var xmlNameSpaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
- serializer.Serialize(new StringWriter(sb), sales, xmlNameSpaces);
- File.WriteAllText("../../../Xml/sales-discounts.xml", sb.ToString());
- }
- //result:
- <sales>
- <sale>
- <car make="Ferrari" model="F430" travelled-distance="214647" />
- <customer-name>Marcelle Griego</customer-name>
- <discount>0.05</discount>
- <price>7243.30</price>
- <price-with-discount>6881.14</price-with-discount>
- </sale>
- <sale>
- <car make="Ferrari" model="250 GTO" travelled-distance="213647" />
- <customer-name>Hipolito Lamoreaux</customer-name>
- <discount>0.1</discount>
- <price>6073.98</price>
- <price-with-discount>5466.58</price-with-discount>
- </sale>
- <sale>........
Advertisement
Add Comment
Please, Sign In to add comment