将LINQ结果加载到具有计算的属性(列)的ViewModel中



我已经看到了一个场景,其中viewModel用一个linq查询填充了,如下所示。问题:如何填充TotalSale属性(列( - 这是以下ViewModel的销售列的巨大总数? Note :我使用的是带有VS2015的ASP.NET Core的最新版本。

ViewModel:

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 }; 

您认为您将拥有许多:

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()
            };

注意:请记住,您需要调整视图以使用您传递给它的新类型并相应地调整代码。

您不澄清Product的结构,但是可以总和多个值

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)总计多个项目。

这是一个快速的答案。它可能需要根据您的其余代码的外观进行更改。您还可以将查询结果分组为总和。

最新更新