我已经看到了使用一个LINQ查询填充ViewModel的场景,如下所示。 问题:如何填充以下ViewModel的TotalSale
属性(列) - 这是Sale列的总计 - ? 注意:我在VS2015上使用最新版本的ASP.NET Core。
视图模型:
public class CategProdViewModel
{
public string Category { get; set; }
public string ProductName { get; set; }
public float Sale { get; set; }
public float TotalSale { get; set; }
}
控制器:
var innerJoinQuery = from category in categories
join prod in products on category.ID equals prod.CategoryID
select new CategProdViewModel { Category = category.Name, ProductName = prod.Name, Sale = prod.Sale };
答案 0 :(得分:2)
您的观点中会有很多这样的内容:
public class CategProdViewModel
{
public string Category { get; set; }
public string ProductName { get; set; }
public float Sale { get; set; }
public real TotalSale { get; set; }
}
但是你只有最后一个属性TotalSale
一次。因此,请将视图模型更改为:
public class CategProdViewModel
{
public string Category { get; set; }
public string ProductName { get; set; }
public float Sale { get; set; }
}
为您的视图创建此模型并将其传递给您的视图。
public class UseThisOnYourView // Give it another name
{
public List<CategProdViewModel> Items { get; set; }
public real TotalSale { get { return this.Items.Sum(x => x.Sale); } }
}
然后你的查询将是这样的:
var innerJoinQuery = from category in categories
join prod in products on category.ID equals prod.CategoryID
select new CategProdViewModel { Category = category.Name, ProductName = prod.Name, Sale = prod.Sale };
var model = new UseThisOnYourView
{
Items = innerJoinQuery.ToList()
};
注意:请注意,您需要调整视图以使用传递给它的新类型并相应地调整代码。
答案 1 :(得分:0)
您没有澄清Product
的结构,但您可以Sum多个值
var innerJoinQuery = from category in categories
join prod in products on category.ID equals prod.CategoryID
select new CategProdViewModel {
Category = category.Name,
ProductName = prod.Name,
Sale = prod.Sale,
TotalSales = products.Sum(t => t.Sale)
};
如果没有关于代码的更多信息,很难说,prod.sale
可能只是最后一个产品的数量。您可以使用Sum(this IEnumerable<TSource> source, Func<TSource, double> selector)
汇总多个项目的总和。
这是一个快速的答案。它可能需要根据代码的其余部分进行更改。您还可以Group对查询结果求和。