ASP.NET MVC开发ERP:如何实现按公司统计产品数量?
嘿,作为ASP.NET MVC新手敢上手ERP系统,已经很厉害了!针对你要给表格每行添加公司产品数量统计的需求,我来帮你梳理下当前代码的问题,以及更合理的实现思路:
先说说当前写法的小问题
你现在在视图里直接调用item.CountBusinessOffers(item.bId),这种写法会导致表格每渲染一行就发起一次数据库查询,如果表格数据多的话,性能会拉胯,而且也违反了MVC的职责分离原则——视图只负责展示数据,不该直接处理数据库逻辑。
优化方案分步走
1. 把统计逻辑封装成独立服务
先把数据库连接、统计产品数量的逻辑抽成专门的服务类,避免和模型/视图混在一起:
public class BusinessOfferService { // 统计指定公司的产品数量 public int GetProductCountByBusinessId(int businessId) { // 建议把数据库连接逻辑做成可复用的(比如单例或依赖注入),避免重复建立连接 DbHelper.ConnectRemoteDB(); var productsCollection = DbHelper.Database.GetCollection<OfferItem>("products"); // 补全你的过滤逻辑,这里假设产品表有对应公司ID的字段(比如BusinessId) var filter = Builders<OfferItem>.Filter.Eq("BusinessId", businessId); return (int)productsCollection.CountDocuments(filter); } // 进阶:批量统计所有公司的产品数量(性能更优) public Dictionary<int, int> GetAllBusinessProductCounts() { DbHelper.ConnectRemoteDB(); var productsCollection = DbHelper.Database.GetCollection<OfferItem>("products"); // 用MongoDB聚合查询一次统计所有公司的产品数,避免循环查库 var aggregationResult = productsCollection.Aggregate() .Group( item => item.BusinessId, group => new { BusinessId = group.Key, ProductCount = group.Count() } ).ToList(); return aggregationResult.ToDictionary(x => x.BusinessId, x => x.ProductCount); } }
2. 用视图模型(ViewModel)传递数据
不要直接把实体模型传给视图,创建专门的视图模型,提前把统计好的产品数量放进去:
public class BusinessRowViewModel { public int BusinessId { get; set; } // 这里加上你需要展示的其他公司属性,比如公司名称、地址等 public string BusinessName { get; set; } // 提前计算好的产品数量,视图直接展示就行 public int ProductCount { get; set; } }
3. 控制器中提前计算统计数据
在控制器的Action里,先获取所有公司数据,再调用服务计算产品数量,组装成视图模型列表传给视图:
public ActionResult BusinessList() { var offerService = new BusinessOfferService(); // 获取所有公司的基础数据(假设从businesses集合查询) var allBusinesses = DbHelper.Database.GetCollection<Business>("businesses").Find(_ => true).ToList(); // 方案一:单个查询(数据量小的时候用) var viewModelList = allBusinesses.Select(biz => new BusinessRowViewModel { BusinessId = biz.Id, BusinessName = biz.Name, ProductCount = offerService.GetProductCountByBusinessId(biz.Id) }).ToList(); // 方案二:批量查询(数据量大的时候优先用,性能更好) // var productCountDict = offerService.GetAllBusinessProductCounts(); // var viewModelList = allBusinesses.Select(biz => new BusinessRowViewModel // { // BusinessId = biz.Id, // BusinessName = biz.Name, // ProductCount = productCountDict.TryGetValue(biz.Id, out var count) ? count : 0 // }).ToList(); return View(viewModelList); }
4. 视图里简化展示
现在视图只需要直接绑定视图模型的ProductCount属性,不用再调用方法了:
<table> <thead> <tr> <th>公司名称</th> <th>产品数量</th> <!-- 其他表头 --> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td>@Html.DisplayFor(modelItem => item.BusinessName)</td> <td>@Html.DisplayFor(modelItem => item.ProductCount)</td> <!-- 其他列 --> </tr> } </tbody> </table>
给新手的额外提示
- 记得处理数据库连接的释放,如果
DbHelper支持的话,尽量用using语句包裹连接逻辑,避免连接泄漏。 - 后续可以尝试用**依赖注入(DI)**来注入
BusinessOfferService,而不是在控制器里直接new,这样代码会更易测试和维护。 - 如果你的数据库是SQL Server而非MongoDB,统计逻辑的思路是一样的:用LINQ的
Count()或者SQL聚合函数提前计算,再把结果放到视图模型里。
内容的提问来源于stack exchange,提问作者Eli Chitrit
相关产品推荐
相关产品推荐

