Does accessing the database from ViewModel violate the MVC principle?

I am writing an application in MVC2 using Entity Framework

As I know ViewModel has to contain only data without any logic to database. Suppose I have Product class that is ADO.NET entity that has EntityCollection<ProductToStatus> when ProductToStatus is many-to-many table. I have ProductModel (that takes Product in its .ctor) which is passed to View.

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

In View I need to render all statuses of the product, so to do it I need to query the DB by item.ProductToStatus.Select(s=>s.ProductStatus).ToList(); in the ProductModel, but this sends request to the DB and thus does it violates the MVC principle?

Is this OK or I need to do something?


you shouldn't do this. Your controller should collect the data required for your view and should package it up and pass it to the view for it to render.

So your ProductModel should either take the details of the Product it needs in its constructor or through properties (my preference) or should, at a push, use the Product it is given to do all the querying in the constructor to set all of its internal fields but not keep a reference to the Product around. I don't like the using the Product in the constructor particularly as its doing work in the constructor which is not great, but depending on what it is doing exactly it might be ok.

Its probably better to make your ProductModel have a load of properties, then you can create it like so:

var model = new ProductModel()

Need Your Help

Cognos 8 API Integration with report integration cognos

I wanted to integrate cognos 8 and fetch the reports in excel/xml/csv format from cognos server. I don't have much knowledge about cognos, so can you provide me some pointers to start this process.