我有一个局部视图,循环遍历其模型(事物列表)以显示thing.Name和三个整数值,它们是相关实体的计数.
首先,我尝试了:(伪剃刀)
foreach(thing in Model){
@thing.Name :
@thing.related.entities.where(condition1).Count()
@thing.related.entities.where(condition2).Count()
@thing.related.entities.where(condition3).Count()
}
Run Code Online (Sandbox Code Playgroud)
但它真的很慢......所以我在ThingRepository中创建了一个函数,它可以更快地执行相同的查询,就像这样(伪代码)
function GetCountofRelatedEntities(relatedID,condition){
return db.entities.where(relatedID==relatedID && condition).count()
}
Run Code Online (Sandbox Code Playgroud)
它的速度要快得多,所以我想称之为.我想我应该从控制器调用它,但是我需要一个ViewModel来保存(thing,int,int,int)集合作为模型,或者我可以极大地使用ViewBag将结果传递给视图,但是,这是一个问题:为什么不简单地从视图中使用存储库?视图中的这段代码有什么问题?(伪剃刀)
@repo=new ThingRepository()
foreach(thing in Model){
@thing.Name :
@repo.GetCountofRelatedEntities(thing.relatedID,condition1)
@repo.GetCountofRelatedEntities(thing.relatedID,condition1)
@repo.GetCountofRelatedEntities(thing.relatedID,condition1)
}
Run Code Online (Sandbox Code Playgroud)
你能告诉我为什么我不应该在View中实例化存储库吗?或者我能做到吗?