我有一个ProductForReturnDTO
,我希望从Product
模型中进行映射。在映射过程中,我想从称为AverageRating
的方法映射"CalculateAverageRating"
。此方法将基于ProductReview
集合中的总记录计算平均评分。
但是我得到了错误:
当试图在映射中包括此方法时,“ ICollection”不包含“ CalculateAverageRating”的定义,并且没有可访问的扩展方法“ CalculateAverageRating””。
有人可以建议我吗?
产品型号
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<ProductReview> ProductReviews { get; set; }
public Product()
{
ProductReviews = new Collection<ProductReview>();
}
}
ProductForReturnDTO
public class ProductForReturnDto
{
public int Id { get; set; }
public string Name { get; set; }
public int AverageRating { get; set; }
public ICollection<ProductReviewForReturnDto> ProductReviews { get; set; }
}
产品评论模型
public class ProductReview
{
public int Id { get; set; }
public int Rating { get; set; }
public string Review { get; set; }
public Product Product { get; set; }
public int ProductId { get; set; }
}
CalculateAverageRating
public static class Extensions
{
public static int CalculateAverageRating(this ICollection<ProductReview> productReviews)
{
var totalReviews = productReviews.Count;
var totalRatings = productReviews.Sum(pr => pr.Rating);
var maxRatings = totalReviews * 5;
int averageRatings = (totalRatings / maxRatings) * 5;
return averageRatings;
}
}
映射器配置文件
public ProductProfiles()
{
CreateMap<Product, ProductForReturnDto>()
.ForMember(dest => dest.AverageRating, opt => {
opt.MapFrom(d => d.ProductReviews.CalculateAverageRating());
});
}