I am new to MVC and new to using EF. In our application we are using Database first approach. As we are using DB first approach, we are geneting edmx from the db.
When I generate the edmx, it generates all the related classed for the tables in my database. Here only I am confusing a lot whether to use the generated classed in my views directly or should I create one more layer of classes on top of the EF generated classed and use them from my controllers and views.
If I am creating one more layer of classes on top of entities I have to take care of mapping in betweeb these classes. I doubt that could be a pain in the future if there is any change in the model.
If I am directly using the entities from my controllers, I feel I am exposing all the unnecessary things to the controllers and views.
Can somebody please advise me how to proceed on this?
You are doing it fine just how you have it, you don't need to change it. You should be able to use the generated classes or if you think you are exposing too much, you can make a view model that you will populate with just the data you care about and pass that to the view. This is how MVC is supposed to work.
Say you have a database table called Articles
and there is a lot of stuff in there that you don't wan't to pass to the view, you could create a view model like this
public class ArticlesViewModel
{
[Required] // this is optional, just to give you an idea of validation
public string Title { get; set; }
public DataTime Date { get; set; }
}
Now in your controller you would have something like this:
ArticlesViewModel articleVM = new ArticlesViewModel();
// populate it from your DB
return View(articleVM);
So now your view only has the Title
and Date
, (you should also have ID
so you can retrieve the full Article
from the DB easily.)
This will give you an idea of just grabbing the needed info from your DB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With