我想使用AutoMapper将三个表的数据转换为平面ViewModel。
由于我不知道如何设置必要的AutoMapper配置,因此,感谢您提供有关如何解决此问题的信息。
extension UIButton {
func addRightImage(image: UIImage, offset: CGFloat) {
self.setImage(image, for: .normal)
self.imageView?.translatesAutoresizingMaskIntoConstraints = false
self.imageView?.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0.0).isActive = true
self.imageView?.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -offset).isActive = true
}
}
我的视图模型:
public class Category {
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public virtual ICollection<BankingAccountCategory> BankingAccountCategories { get; set; }
}
public class BankingAccountCategory {
public int Id { get; set; }
public int BankingAccountId { get; set; }
public int CategoryId { get; set; }
public virtual BankingAccount BankingAccount { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<Expense> Expenses { get; set; }
}
public class Expense {
public int Id { get; set; }
public int BankingAccountCategoryId { get; set; }
public DateTime Date { get; set; }
public decimal Amount { get; set; }
public virtual BankingAccountCategory BankingAccountCategory { get; set; }
}
在sql方面,此查询提供了我想要的结果:
public class CategoryViewModel {
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int NumberOfExpenses { get; set; }
}
我的自动映射器配置:
select cat.Id, cat.Title, cat.Description, count(ex.Id) as ExpenseCount from Category cat
inner join BankingAccountCategory bac on bac.CategoryId = cat.Id
left outer join Expense ex on ex.BankingAccountCategoryId = bac.Id
group by cat.Id, cat.Title, cat.Description
问题在于,所有条目的NumberOfExpenses始终为0。
答案 0 :(得分:1)
您的原始配置将返回IEnumerable<ICollection<Expense>>
,而不是所需的int
。
尝试以下方法:
CreateMap<Category, CategoryViewModel>()
.ForMember(dest => dest.NumberOfExpenses,
opt => opt.MapFrom(cat => BankingAccountCategories.Sum(bac => bac.Expenses.Count())));