I am currently building a blog posting web application using MVC 4 in C# mostly for the purpose of honing my knowledge of application architecture.
Currently it is in a tiered structure as:
View > View Model > Controller > Data Access Layer > Data Store
There may be a Service Layer added between the Controller and Data Access Layer later but that is not the reason for this particular question.
What should the parameters and return types of Data Access Layer methods be?
My current understanding is the View Models exist to provide the View with data that may be more or less than the Domain Model's structure exposes.
In my application, a Post consists of the PostId, Description, Content & UserId. There is also a Users table that has a UserId and UserFullName.
The Post Model mirrors the Posts table in that it stores the UserId but not the UserFullName. As such, when I need to retrieve the Post details along with the UserFullName to pass to the View, what should be returned by the DAL method? I have created a new Domain Model which contains all the data required by the View, but this goes against the fact that the Domain Models be de-coupled from its implementation. I'm of the thinking that just an Object can be returned when I query the database for the Post data, plus whatever else is needed by the View.
Is a wholly generic data access layer required here or is it overkill?
In EF exists the method Include
which let you to preload records from related tables.
public ActionResult Index()
{
var model = context.Posts.Include("Users");
return View(model);
}
In .cshtml
:
@model IEnumerable<Post>
@foreach(var post in Model)
{
<p>@post.Description</p>
@Html.Raw(post.Content)
<p>By @post.Users.UserFullName</p>
}
See http://msdn.microsoft.com/en-us/data/jj574232.aspx for more details.