Pet*_*eto 2 c# asp.net-mvc entity-framework repository razor
我有一个局部视图,循环遍历其模型(事物列表)以显示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中实例化存储库吗?或者我能做到吗?
为什么不简单地从视图中使用存储库?
因为你违反了MVC设计模式.视图的责任不是获取数据.它是以视图模型的形式显示从控制器传递给它的数据.就这么简单.
您可以在视图中调用存储库或任何您喜欢的内容,但不要再使用asp.net-mvc标记您的问题,因为您不再使用任何MVC.我的意思是你可以做任何你喜欢的事情 - 你甚至可以在你的视图中编写SQL查询.
但MVC设计模式的重点是将数据检索逻辑与表示逻辑分开.
| 归档时间: |
|
| 查看次数: |
1086 次 |
| 最近记录: |