Are there Visual Studio Tools For Creating DTO/ViewModel - asp.net-mvc

I'm trying to introduce ASP.Net MVC to my department. I am encouraging them to have a ViewModel per View and AutoMapper for our larger projects (and ideally in general).
Sometimes this means having one large entity and picking 5 of its properties and creating the ViewModel. This is done by looking at the the edmx model (many projects were existing so it was DB first) and then creating matching properties in a ViewModel class. Obviously names etc have to match for AutoMapper to work. Also for navigation properties you have to add the navigation name first. Ideally also being able to type in a display name etc.
I'm trying to ease them into doing this (what they see as extra work). Is there any tool that would load a list of fields and allow you to select via checkbox etc and create the class from that?
I guess the same would apply to DTOs etc
Thanks

Have you tried this http://www.codesmithtools.com/product/generator
you can create a template of the dto and then it will generate the files/dto's for you as needed from any kind of datasource.

Related

MVC5 option group maintenance table for CRUD

What is the best approach for maintaining (CRUD) on an optiongroup list that is driven by two sql server tables?
The option group is like this and is driven simply by two tables (parent child)
OptionGroupOne
ItemOne
ItemTwo
OptionGroupTwo
SecondItemOne
SecondItemTwo
etc…………….
Was thinking of just looping through in an unordered list?
I’m using entity framework 6 with MVC5 don't really want to use javascript.
This is a long way if you don't seem to have anything ready yet... I bet that's the reason why no one wants to start explaining.
You should organise the Lists in nested ViewModels, the OptionGroupViewModel and the ItemViewModel. The OptionGroupViewModel has a string property for the name and a List<ItemViewModel> property for the children. So the main model should be a List<OptionGroupViewModel>.
In your cshtml, Using the Html.EditorForModel() extension method on a the latter, you should get some View Results already, the EditorFor... methods are quite intelligent and will generate views based on the data structure.
Now you will need a MVC Post method with the List as the model and you will find all updates there, You need to map them back to the Entity Framework model (or whatever kind of base model you have). As you mentioned in your comment above, you want just a "way of editing the titles of each option group and the title of each group". This would be pretty simple but is half way to CRUD, and Delete + Add are much trickier in that scenario.
Using frameworks like Knockout JS is a big gain here but requires some learning and will introduce JavaScript to your project. The linked tutorial is for Web.Api but it will also work for MVC.

Razor view display domain model properties without knowing the domain model

Background: I have a simple mapping app (backed by GeoServer) that allow a user to click on a feature and select a data table displaying information about the selected feature. A HTML table would then be inserted under the map to show the query results.
Problem: Since there are at least 40 something tables that the user can select, I don't want to build 40+ partial views. Is it possible to build a Razor view that can handle any model passed to it and build a HTML table without knowing the domain model's structure? I'm leaning toward no after some poking around.
Reference: Related to my previous question of
Dynamic DBSet lookup and query
Practically, asp.net mvc already does that when you call EditorForModel, DisplayForModel or similar. If there is no developer defined view for corresponding model type, it calls object template, which uses reflection to render editor and display views. That template does not have predefined knowledge of model type.
You could set model type to object for view, and make use of reflection to generate tables.

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.

ASP.NET MVC: using EF entities as viewmodels? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
ASP.NET MVC - Linq to Entities model as the ViewModel - is this good practice?
Is is OK to use EF entities classes as view models in ASP.NET MVC?
What if viewmodel is 90% the same of EF entity class?
Let's say I have a Survey class in Entity Framework model. It 90% matches data required for view to edit it.
The only difference from what view model should have - is one or several properties to be used in it (that are required to populate Survey object because EF class cannot be directly mapped onto how it's properties are represented (sub-checkboxes, radio groups, etc.))
Do you pass them using ViewData[]? Or create a copy of Survey class (SurveyViewModel) with new additional properties (it should be able to copy data from Survey and back to it)?
Edit:
I'm also trying to avoid using Survey as SurveyViewModel property. It will look strange when some Survey properties are updated using UpdateModel or with default binder, while others (that cannot be directly mapped to entity) - using SurveViewModel custom properties in controller.
I like using Jimmy Bogard's approach of always having a 1:1 relationship between a view and a view model. In other words, I would not use my domain models (in this case your EF entities) as view models. If you feel like you are doing a lot of work mapping between the two, you could use something like AutoMapper to do the work for you.
Some people don't like passing these model classes all the way through to the view, especially as they are classes that are tied to the particular ORM you're currently using. This does mean that you're tightly binding your data framework to your view types.
However, I have done this in several simple MVC apps, using the EF entity type as the Model for some strongly-typed views - it works fine and is very simple. Sometimes simple wins, otherwise you may find yourself putting a lot of effort and code into copying values between near-identical Model types in an app where realistically you'll never move away from EF.
You should always have view models even if they are 1:1. There are practical reasons rather than database layer coupling which I'll focus on.
The problem with domain, entity framework, nhibernate or linq 2 sql models as your view classes is you cannot handle contextual validation well. For example given a user class:
When a person signs up on your site they get a User screen, you then:
Validate Name
Validate Email
Validate Password Exists
When an admin edits a user's name they get a User screen, you then:
Validate Name
Validate Email
Now expose contextual validation via FluentValidation, DataAnnotations Attributes, or even custom IsValid() methods on business classes and validate just Name and Email changes. You can't. You need to represent different contexts as different view models because validation on those models changes depending on the screen representation.
Previously in MVC 1 you could get around this by simple not posting fields you didn't want validated. In MVC 2 this has changed and now every part of a model gets validated, posted or not.
Robert Harvey pointed out another good point. How does your user Entity Framework display a screen and validate double password matching?
On bigger projects, I usually split up business objects from data objects as a matter of style. It's a much easier way to let the program and database both change and only affect the control (or VM) layer.

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.

Resources