【问题标题】:Does accessing the database from ViewModel violate the MVC principle?从 ViewModel 访问数据库是否违反 MVC 原则?
【发布时间】:2023-04-06 03:55:01
【问题描述】:

我正在使用实体框架在 MVC2 中编写应用程序

据我所知,ViewModel 必须只包含数据,而不包含任何数据库逻辑。假设我有 Product 类,它是具有 EntityCollection<ProductToStatus> 的 ADO.NET 实体,而 ProductToStatus 是多对多表。我有ProductModel(在其.ctor 中采用Product),它被传递给View

public class ProductModel
{
    ....
    public Product Item {get; private set;}
    ...
    public ProductModel(Product item)
    {
         ...
         this.Item = item;
         ...
    }
}

View 中,我需要渲染产品的所有状态,因此我需要在ProductModel 中通过item.ProductToStatus.Select(s=>s.ProductStatus).ToList(); 查询数据库,但这会向数据库发送请求,因此是否违反了MVC原理?

这样可以吗?还是我需要做点什么?

【问题讨论】:

    标签: c# asp.net-mvc entity-framework asp.net-mvc-2


    【解决方案1】:

    你不应该这样做。您的控制器应该收集视图所需的数据,并将其打包并将其传递给视图以进行渲染。

    因此,您的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
        }
    

    【讨论】:

      【解决方案2】:

      是的,它违反了模式。您应该在 Controller 中填充 ViewModel,然后将其传递给您的视图。

      当然它会起作用,但这不是模型-视图-控制器的想法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-15
        • 2014-02-15
        • 2010-11-29
        • 2012-03-02
        • 2020-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多