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
ProductModelshould either take the details of theProductit needs in its constructor or through properties (my preference) or should, at a push, use theProductit is given to do all the querying in the constructor to set all of its internal fields but not keep a reference to theProductaround. I don’t like the using theProductin 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
ProductModelhave a load of properties, then you can create it like so: