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

Loading LINQ results into a ViewModel that has a calculated attribute (column)

我见过这样的场景,其中 ViewModel 填充了一个 LINQ 查询,如下所示。 问题:如何填充以下 ViewModel 的 TotalSale 属性(列)——即销售列的总计? 注意:我在 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 }; 

你没有弄清楚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查询结果求和

你会看到很多这样的东西:

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

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