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?
2 Answers 2
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.
2 Comments
AccountModels.cs
in a default MVC3 app. These only expose the info that the user can see and change. Then on a post, it updates the Membership
(i think) table. Membership contains a lot more properties than just username, password, etc. Hope that helps. See asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/… You probably want to use NuGet to install one of the POCO (Plain Old C# Objects - objects that have no dependencies on other functionality such as EF) generators so you can pass your objects up to the View layer without the View layer requiring knowledge of EF at all.
This is called "separation of concern", or "single responsibility principle" - your Views know about how to display data, your DAL knows how to retrieve and store data, and neither should have to know the intimate bits about doing the others job.
If you pass EF objects up the chain, then you also need to pass the EF knowledge and abilities up the chain - passing POCOs bypasses this.
Take a look at this SO topic:
3 Comments
Explore related questions
See similar questions with these tags.