gpt4 book ai didi

c# - 为什么不在 View 中使用存储库

转载 作者:行者123 更新时间:2023-11-30 19:02:48 25 4
gpt4 key购买 nike

我有一个循环遍历其模型(事物列表)以显示事物名称和三个整数值的部分 View ,这些整数值是相关实体的计数。

首先,我尝试放置:(伪 Razor )

foreach(thing in Model){
@thing.Name :
@thing.related.entities.where(condition1).Count()
@thing.related.entities.where(condition2).Count()
@thing.related.entities.where(condition3).Count()
}

但它真的很慢...所以我在 ThingRepository 中创建了一个函数来更快地执行相同的查询,就像这样(伪代码)

function GetCountofRelatedEntities(relatedID,condition){
return db.entities.where(relatedID==relatedID && condition).count()
}

而且速度更快,所以我想调用它。我想我应该从 Controller 调用它,但是我需要一个 ViewModel 来保留一个 (thing, int, int, int) 集合作为模型,或者我可以使用 ViewBag extremely 将结果传递给 View ,但是,这是问题:为什么不简单地从 View 中使用存储库? View 中的这段代码有什么问题? (伪 Razor )

@repo=new ThingRepository()
foreach(thing in Model){
@thing.Name :
@repo.GetCountofRelatedEntities(thing.relatedID,condition1)
@repo.GetCountofRelatedEntities(thing.relatedID,condition1)
@repo.GetCountofRelatedEntities(thing.relatedID,condition1)
}

您能告诉我为什么我不应该在 View 中实例化存储库吗?或者我可以做到吗?

最佳答案

Why not simply use the repository from the view?

因为你违反了 MVC 设计模式。 View 的职责不是获取数据。它以 View 模型的形式显示从 Controller 传递给它的数据。就这么简单。

您可以在 View 中调用存储库或任何您喜欢的名称,但不要再使用 asp.net-mvc 标记您的问题,因为您不再使用任何 MVC。我的意思是您可以做任何您喜欢的事情——如果您愿意,您甚至可以在您的 View 中编写 SQL 查询。

但是 MVC 设计模式的重点是将数据检索逻辑与表示逻辑分开。

关于c# - 为什么不在 View 中使用存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9026002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com