I am trying to understand the whole MVC/EF relationship. If I create a Entity Model that would only interact with the database (since you shouldnt pass you entity model to a view), then a class for the Model, and finally a view model all shown below. My only question is it seems redundant to have the second class, the only different in the examples I have seen is that they apply data annotations to that class since it is interacting with the view. Why is it so important to make sure that entity objects arent exposed at the view layer?
I havent actually started writing a project yet, but I assume that you would use the Entity model for interacting with a database then cast it into a ProductModel to pass to the view is this the correct logic?
Entity Model:
public class Product
{
[Key()]
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public double Price { get; set; }
}
Model:
public class ProductModel
{
public int ID { get; set; }
[StringLength(50)]
[Required(ErrorMessage = "Product Name is required.")]
[Display(Name = "Product Name")]
public string Name { get; set; }
public string Description { get; set; }
public double Price { get; set; }
}
ViewModel:
public class ProductViewModel
{
Product myProduct { get; set; }\
//Plus any other properties I may need for the view.
}
UPDATE:
In the example I have been reading they also have a DBContext set as follows. So is the ProductModel class useless then?
public class MyAppContext : DbContext
{
public MyAppContext()
: base("name=DBConnection")
{
}
public DbSet<Product> Products { get; set; }
}