MVC3 EF model-first with POCO and ViewModels - entity-framework-4

Lots of great posts out here on this topic and I've tried to read them all. I'm a long time n-tier developer but trying to swing into action with an MVC3/EF application. I've generated POCOs via the EF POCO generator(T4). I'm also binding ViewModels to my Views...no EF stuff in my Views. My question has to do with validation (U/I only). I like the idea of DataAnnotations and want to use them. However, to use them correctly I have to use them in my ViewModels. From the advice I see on this site and others, I'll have to replicate any properties from my POCOs into my view models and do my annotations there. To make this easier I've seen lots of suggestions to use AutoMapper to make this tedious mapping more bearable.
Do I pretty much have the right idea?

I'm also binding ViewModels to my Views...no EF stuff in my Views
Correct. Ideally, your POCO's should not be on your Views.
I like the idea of DataAnnotations and want to use them. However, to use them correctly I have to use them in my ViewModels
Correct. There shouldn't be any data annotations on your POCO's.
From the advice I see on this site and others, I'll have to replicate any properties from my POCOs into my view models and do my annotations there
Why? Are you always binding to all of the properties on your POCO's? Remember, the ViewModel is to serve the View only. So if you have a form to submit an order, the ViewModel should only contain what is required to persist that Order. A combination of AutoMapper and your custom code can then map that to your POCO.
To make this easier I've seen lots of suggestions to use AutoMapper to make this tedious mapping more bearable
#Craig is right, it has nothing to do with Data Annotations. AutoMapper maps your ViewModel to your domain models with a few lines of configuration.

AutoMapper is only about transformation from entity to view model and vice versa. It is just replacement of code like custom conversion operator between types. You will still have to create your view models and mark properties with correct data annotations.

Related

MVC, Strongly Typed Views and Entity Framework dilemma

I've read quite a few Q & As relating to logic in views within an MVC architecture and in most cases I agree that business logic shouldn't live in a view. However having said this, I constantly question my approach when using Microsoft's MVC Framework in conjunction with the Entity Framework because of the ease of accessibility to foreign key relationships a single entity can give me which ultimately results in me performing Linq to Entities queries inline within a View.
For example:
If I have the following two entities:
Product ([PK]ProductId, Title, Amount)
Image ([PK]ImageId, [FK]ProductId, ImageTitle, DisplayOrder)
Assuming I have a strongly typed Product view and I want to display the primary image (lowest display order) then I could do something like this in the view:
#{
Image image = (from l in Model.Image
orderby l.DisplayOrder
select l).FirstOrDefault();
}
This is a simple example for demonstration purposes, but surely this begins to bend the rules in relation to MVC architecture, but on the other hand doing this in the Controller and then (heaven forbid) jamming it into the ViewBag or ViewData would surely be just as much of a crime and become painful to manage for more than a few different related classes.
I used to create custom classes for complex Models, but it's time-consuming and ugly and I no longer see the point as the Entity Framework makes it quick and easy to define the View to be the primary Model (in this case a Product) and then easily retrieve all the peripheral components of the product using Linq queries.
I'd be interested to know how other people handle this type of scenario.
EDIT:
I also quite often do things like:
#foreach(Image i in Model.Image.OrderBy(e => e.DisplayOrder).ToList())
{
<img ... />
}
I'm going the 'custom classes for Models' way, and I agree it's time consuming and mundane, hence tools like http://automapper.codeplex.com/ have been created, to accompany you with this task.
Overall, I'm having similar feelings to yours. Reading some stuff saying it's good to have your domain model unrelated to your storage, then different class for your view model than the domain model, and then seeing that libraries actually seem to 'promote' the easy way (data annotations over your domain classes seem to be simplier than EF fluent interface etc etc).
At least we've got the choice I guess!
Model binding There is also issue that when you want to POST back the model data and store it in the database, you need to be careful and make sure MVC model binders bind all fields correctly. Else you may loose some data. With custom models for views, it might be simplier.
Validation
MVC gives you a way to validate using attributes, when you use viewmodels, you can freely pollute it with such annotations, because it's view specific (and validation should be view/controller action specific as well). When you use EF classes, you would be polluting those classes with unrelated (and possibly conflicting) logic.

Is it bad practice to use a lot of viewmodels in asp.net mvc

Been working on a pet project on the side to learn asp.net mvc better. My question is about viewmodels in mvc. I understand the controller is supposed to handle the interaction between the view and the model. I feel like I keep having to create viewmodel classes to combine information from the models to pass to the view.
Is this bad practice? Should I be doing more of the logic elsewhere and cut down on the viewmodels?
At the moment I've almost got a viewmodel for just about every one of my main views. But I definitely don't want the view to access the model directly.
No, all your views should be strongly typed, so using for each view one viewmodel is best practice. Here is very nice article about viewmodels.
The more viewmodels you use the better. The viewmodels allow you to create a single object that can contain different types of data from your models. These are very useful when creating templates. Also, this is very useful when using JQuery and Ajax since its a nice way to pass data into your controller and then directly to the DOM. In my opinion, use as many viewmodel as you desire.
Another thing that you might consider is to try to have better design of your model. I personally try to build my model just like a sql database and follow the normalization forms. You should not have to create a new viewmodel for each view in addition to the models you already have. If you need to pass information to the view that is not part of the model you are using, use ViewData or ViewBag. These are passed as an object so you will have to cast them to the appropriate class.
Nothing bad in this. As much your viewmodel closer to view as better.
Model could not particullary match View, so you use ViewModel class for that.
Great answers here, and here is my view on why a lot of view models are not an issue.
Your ViewModels are a nice way of separating your pure Data Access Objects or even your Domain Objects from your presentation layer and provide a dumbed down version of those objects for your views to consume.
Your views are supposed to be dumb and for me personally, what I try to achieve is to massage my domain model into a ViewModel for my view to consume.
Using lot of viewmodels creates mess in your project. It is much better to just create a Tuple in the controller then pass it.

How to create model quickly&elegantly with Linq To Sql in asp.net mvc?

Ok straight to the issue. I can get object mapping to tables easily with Linq To Sql. For instance: class Product, class Order, class Order_Detail from Northwind. IMO, these 3 object have already met model's meet. But i can't put some useful attr([Required] [HttpPost]) on properties of them(except modifying design.cs, which is not recommended).Do i have to create ProductModels OrderModels with the same properties myself, and maybe some additional DAL-like classes to turn the linq2sql objects to models??
EDIT:
Even if i put design.cs and my models in the same namespace, how can i make two partial classes have the same properties??
Yes, you should create DTO's for each Linq to SQL model, it is not considered a good practice to pass Linq2Sql objects through your layers.
Optionally, look into to using Entity Framework Code First. It is stupid simple to use and you can add validation attributes directly to your POCOs, which are enforced on the data persistence side as well as the presentation side in MVC.
here's a good EF codefirst primer : http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx

ASP.NET MVC ViewModel Auto Generation

I have a load of ADO.NET Entities in my MVC project. I was going to use these entities directly from my views/controllers... however, I think it's probably best to use ViewModels which more accurately reflect what the View requires.
I'm looking for a way that I can auto-generate a ViewModel from an existing Entity, i.e., auto-generate the wrapper or adapter pattern from an existing member... Or a T4 template that would loop through the public properties of an Entity, and output properties for the ViewModel... then I can delete the properties I don't need or create aggregate view models etc.
I cannot seem to find anywhere a way to auto-gen a wrapper or adapter pattern class from an existing type?
The idea is then at runtime, use AutoMapper to map between the ViewModel and the Entity.
thanks
You could use AutoMapper to convert from your domain model to a view model. There's a great post from Jimmy Bogard explaining how you could integrate this within your controller actions.
http://weblogs.asp.net/rajbk/archive/2010/05/04/a-basic-t4-template-for-generating-model-metadata-in-asp-net-mvc2.aspx
That can help. It is actually for metadata generation for existing entity types. But you can use it to generate clean view models with data annotations as well. Maybe with a little modification.

Using a View Model + Data Model in ASP.NET MVC to support typed views?

How do most developers handle Typed Views in ASP.NET MVC when dealing with large applications? We are considering putting View-specific models in the Models folder, then putting all domain objects into a separate project. This way our Controllers can easily add the domain object to the typed view, without the domain object needing to be aware of the View layout itself.
For example, if we have an Employee object with:
Id
First Name
Last Name
Status
Then our Employee View might use a ViewEmployeeModel object with:
Employee object
List to populate Status drop-down
etc
Is this a sensible approach? Are there better ways to accomplish the same thing? It seems a little strange since I'd basically have two models (one for the view, one for the business objects), but isn't it better than using untyped views?
I do this almost as a rule, because:
It lets you design the app view-first instead of DB-first, which is nice when working with customer representatives.
Views typically have a much "flatter" object graph than, say, Entity Framework models. LINQ makes it easy to map these.
The views and the data model can evolve much more independently.
It's typically easier to model bind to a flat view model with, say, FK IDs than an entity model which expects fully materialized related objects.
You don't have to worry about accidentally exposing "secret" properties or whitelisting properties for updates.
Don't have the reputation to comment, but Craig is right. It's a variation of the Model-View-ViewModel pattern. There's a good article on it available at Los Techies.
The article also uses the AutoMapper code that mgroves pointed out so you should be able to kill two birds with one stone.
I think this is a pretty sensible approach. One thing that might help you out is AutoMapper.
Seems fine, you have the advantage that the model only contains information needed by the view and not lots of pesky business logic functions / values.

Resources