我正在使用 Entity Framework 在 MVC2 中编写应用程序
据我所知,ViewModel 必须只包含数据,而没有任何数据库逻辑。假设我有 Product
类,它是 ADO.NET 实体,当 EntityCollection<ProductToStatus>
是多对多表时,它具有 ProductToStatus
。我有传递给 ProductModel
的 Product
(在其 .ctor 中采用 View
)。
public class ProductModel
{
....
public Product Item {get; private set;}
...
public ProductModel(Product item)
{
...
this.Item = item;
...
}
}
在
View
中,我需要呈现产品的所有状态,为此我需要通过 item.ProductToStatus.Select(s=>s.ProductStatus).ToList();
中的 ProductModel
查询数据库,但这会向数据库发送请求,因此是否违反了 MVC 原则?这可以吗,还是我需要做点什么?
最佳答案
你不应该这样做。您的 Controller 应该收集您的 View 所需的数据,并将其打包并将其传递给 View 以进行渲染。
因此,您的 ProductModel
应该在其构造函数中或通过属性(我的偏好)获取它需要的 Product
的详细信息,或者应该在推送时使用 Product
它在构造函数中执行所有查询以设置其所有内部字段但不保留对 Product
的引用。我不喜欢在构造函数中使用 Product
,特别是因为它在构造函数中所做的工作并不好,但取决于它究竟在做什么,它可能没问题。
让您的 ProductModel
拥有大量属性可能更好,然后您可以像这样创建它:
var model = new ProductModel()
{
Statuses=product.ProductToStatus.Select(s=>s.ProductStatus).ToList(),
Name=product.Name,
OtherProperty=GetPropertyValue(product),
//etc
}
关于c# - 从 ViewModel 访问数据库是否违反了 MVC 原则?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8342279/