ValueInjecter does it have these automapper features? - asp.net-mvc

I am currently using auto mapper and I think it is a good tool but I don't like how it can't handle view model to domain situations. It kinda sucks that I have to go in the automapping and map each one.
I been looking around and been reading about valueinjecter and how it can handle this. I am wondering though can it do these features what automapper has?
Can you make something like resolvers and formatters?
Can you combine values. For instance on the client side I have a datetime but it is broken into 2 different textboxes(one has a timepicker one has a datepicker). Of course in the database it is stored as one field.
So in my domain(what is later used with nhibernate) I have DateTime DateChoosen. In my view model I would have String Date, String Time.
Right now in automapper I have a resolver(or formatter I can't remember) that takes both of the view model values and converts it into a DateTime and then maps it to the domain.
Can I do something like this in valueinjecter?
I also been looking around and found this Automapper simulation with the ValueInjecter. I am wondering if this would have all the automapper features or if it just makes the syntax look like automapper.
If it actually uses automapper too, does anyone know if they keep using the most current versions?

It's a different concept, it's not the exact same thing so it doesn't have formatters and resolvers, it only has ValueInjections which are applied when injecting from one object to another
the exact scenario that you are describing is shown in prodinner sample, here:
http://code.google.com/p/prodinner/source/browse/trunk/WebUI/Mappers/DinnerMapper.cs
DinnerMapper inherits this:
http://code.google.com/p/prodinner/source/browse/trunk/WebUI/Mappers/Mapper.cs

Related

MVC ViewModel approaches and mapping. Best approach

I've been looking at the different approaches to solving the mass assignment issues with MVC as well as doing things the right way.
So far, the 2 approaches which I think are the best are below: (I have also looked at AutoMapper)
1: Value Injecter - This seems to do the job pretty well, but also relies on a third party library
2: Using the UpdateModel method and bind to a View Model interface which exposes a subset of the required properties in your domain model. http://www.codethinked.com/easy-and-safe-model-binding-in-aspnet-mvc
Before I jump in and code my whole application (without spending a week on each to find out which one I actually like) using one of the above practices, does anybody have real world experience of using these 2 methods and which one you would recommend?
in simple scenarios where you have only text fields matching strings/int properties anything will do just as well.
but when you have properties on the viewmodel that match objects in the model (FK in the DB) it gets a bit more complex, you might need to pull data from the DB for some individual props and map some property of that object to the ViewModel, stuff like that.
prodinner asp.net mvc demo application uses valueinjecter in Mapper classes, there's a pdf where this approach is explained, you can download it here: http://prodinner.codeplex.com/
General consensus from all the reading I've done on this topic is that if you're going from a Entity or Domain Model (from your database) to a View Model to show on the form feel free to use automation tools like AutoMapper or whatever your preferred tool is to automate it.
If you are however going from a Input or Form Model (the object populated via the automatic model binding) back into to your Entity or Domain Model, do not automate this. It's a slippery slope to navigate correctly and can result in your automation tool mapping over fields that were not intended/permitted. Everything I've read about this (and various implementations myself) suggest the best practice is to do this manually/explicitly. It's pretty straight forward and object initializers can make it very easy to read.
var person = new Person()
{
PersonId = model.PersonId,
FirstName = model.FirstName,
LastName= model.LastName
}
personService.UpdatePerson(person);
Something along that line.

Why is System.ComponentModel.DataAnnotations.DisplayAttribute sealed?

I was going to implement a custom DisplayAttribute in order to allow dynamic display values based on model values, but I can't because DisplayAttribute is sealed.
Before I go off and write my own customer attribute that emulates the behavior of DisplayAttribute, can anybody think of why this is sealed? I'm assuming there is a reason behind it, and if so, that may be the same reason I shouldn't try to "hack" around this limitation by rolling my own.
I'm not asking anyone to read Microsoft's mind, I'm just hoping someone already knows the by-design reason it's sealed, so that I can take that into account when rolling (or avoiding) my own implementation.
In general it is considered best practice to seal attributes. FxCop has a rule about it, defined here. From that page:
The .NET Framework class library provides methods for retrieving custom attributes. By default, these methods search the attribute inheritance hierarchy; for example Attribute.GetCustomAttribute searches for the specified attribute type, or any attribute type that extends the specified attribute type. Sealing the attribute eliminates the search through the inheritance hierarchy, and can improve performance.
Many of the MVC attributes (ActionFilter, etc) are unsealed because they are specifically designed to be extended, but elements in the DataAnnotations namespace are not.
Not exactly what you asked, but following your intent...
You can still allow for dynamic display values, you just wont extend the DisplayAttribute.
Instead, you can implement your own IModelMetadataProvider which could contain any logic needed to create dynamic display values.
Brad Wilson, from the ASP.NET MVC team, has a good article and sample of this on his blog: http://bradwilson.typepad.com/blog/2010/01/why-you-dont-need-modelmetadataattributes.html

Best practice question - Working straight with Linq to sql classes

This is possibly a bit of a stupid question, but I am getting confused due to the ASP.NET MVC book I am currently reading...
Working with Linq-To-SQL it seems to say that it is not good practice to pass the Linq-to-SQL objects straight to the controller, but that each object should be modelled separately first and this should be passed between the controller and the repository.
Say, I have a database of products. Linq-to-SQl creates a product class for me with Name, Price and Whatnotelse properties. I could pass that straight from repository to controller and then view, but instead it seems to recommend that I use and third class, say Product_Entity, with also Name, Price etc. properties and pass that to the controller.
I fail to see the benefit of this approach, except possibly for adding attributes to the properties... But apart from that it seems to have more drawbacks than benefits. Say each product has manufacturer information as well, I don't see how I can model that easily in my third class.
Is this approach really best practice? Or did I misunderstand all that? If so, why is it bad to work straight off the linq-to-sql generated objects? And how do you deal with relationships between objects in y
The huge benefit to this other class you create is that, to use your example, it doesn't necessarily map to either a product or a manufacturer. Think about it like this:
Your Linq to SQL classes are meant for talking in the "data" domain.
Your "data" classes (the ones you're having trouble with) are meant for talking in the "application" domain.
Let's take an example. Suppose in your MVC application you wanted to show a grid of information about products. You want to see their Name, Price (from the Product table) and their Country of Manufacture and Manufacturer name (from the Manufacturer table). What would you name this class? Product_Manufacturer? What if later on you wanted to add properties from yet a third table such as product discounts? Instead of thinking about these objects in purely the data domain, think about them with regard to your application.
So instead of Product_Manufacturer, what about calling it ProductSummaryItem? Each property of the ProductSummaryItem class would map 1:1 with a field shown in your grid on the UI. Your controller would perform the mapping between the information in the data domain (Product, Manufacturer) with the custom class you'd created in the application domain (ProductSummaryItem).
By doing this, you get some awesome benefits:
1) Writing your views becomes really, really simple. All you have to do to display your data is loop through the ProductSummaryItems and wrap them in and tags, and you're done. It also allows for simple aggregation. Say for example you wanted to add a field called ProductsSoldLastYear to your ProductSummaryItem class. You could do that very simply in your views because all it is to them is another property.
2) Since the view is trivial and there's mapping logic in the controller, it becomes much easier to test the controller's output because it's customized to what the view is going to see.
3) Since the ProductSummaryItem class only has the data it needs, your queries can potentially become much faster because they only need to query for the fields that would populate your ProductSummaryItem object, and nothing else. This overhead can become overbearing the more data-domain objects make up your ProductSummaryItem object.
This pattern is called Model View ViewModel (MVVM) and is hugely popular with MVC as well as in frameworks like WPF.
The argument against MVVM is that you have to somewhat reimplement simple classes for CRUD operations. Fair enough, I guess, but you can use a tool like automapper to help out with things like that. I think you'll find fairly quickly, though, that using the MVVM pattern even for CRUD pays dividends, because before you know it, even with simple classes, you'll start wishing you had extra fields which can easily drive your views.

When is it right to use ViewData instead of ViewModels?

Assuming you wanted to develop your Controllers so that you use a ViewModel to contain data for the Views you render, should all data be contained within the ViewModel? What conditions would it be ok to bypass the ViewModel?
The reason I ask is I'm in a position where some of the code is using ViewData and some is using the ViewModel. I want to distribute a set of guidelines in the team on when it's right to use the ViewData, and when it's just taking shortcuts. I would like opinions from other developers who have dealt with this so that I know my guidelines aren't just me being biased.
Just to further Fabian's comment; you can explicitly ensure viewdata is never used by following the steps outlined in this article. There's really no excuse not to use models for everything.
If you have no choice but to use ViewData (say on an existing project); at the very least use string constants to resolve the names to avoid using 'magic strings'. Something along the lines of: ViewData[ViewDataKeys.MyKey] = myvalue; Infact, I use this for just about anything that needs to be "string-based" (Session Keys, Cache Keys, VaryByCustom output cache keys, etc).
One approach you may wish to consider as your views become more complex, is to reserve the use of Models for input fields, and use ViewData to support anything else the View needs to render.
There are at least a couple of arguments to support this:
You have a master-page that requires some data to be present (e.g. something like the StackOverflow user information in the header). Applying a site-wide ActionFilter makes it easy to populate this information in ViewData after every action. To put it in model would require that every other Model in the site then inherit from a base Model (this may not seem bad initially, but it can become complicated quickly).
When you are validating a posted form, if there are validation errors you are probably going to want to rebind the model (with the invalid fields) back to the view and display validation messages. This is fine, as data in input fields is posted back and will be bound to the model, but what about any other data your view requires to be re-populated? (e.g. drop-down list values, information messages, etc) These will not be posted back, and it can become messy re-populating these onto the model "around" the posted-back input values. It is often simpler to have a method which populates the ViewData with the..view data.
In my experience I have found this approach works well.
And, in MVC3, the dynamic ViewModels means no more string-indexing!
I personally never use ViewData, everything goes through the Model, except when im testing something and i quickly need to be able to see the value on the view. Strongtyping!
In terms of ASP.NET MVC 2, ViewModel pattern is the preferred approach. The approach takes full advantage of compile time static type checking. This in combination with compiling mvc views will make your development work-flow much faster and more productive since errors are detected during build/compile time as opposed to run time.

How to bind form fields to model properties with different names?

I've got a search form that I want to use short query string parameters for (e.g. ?q=value&s=whatever&c=blah) and I'd like to use MVC model binding to get those parameters into my controller action.
I can create a type that mirrors these short names, but I'd rather have a type that has more sensible names (e.g. q = Query, s = SortOrder, c = Cheese). Is there a nice simple way I can do this, such as attributes on my model?
I know I can write a new model binder for this, but that feels like overkill - I'm not doing anything complicated, just using different names) - and it feels wrong to have to suddenly have to be quite so explicit.
Since the model binding infrastructure uses TypeDescriptors, I guess I could specify a custom type descriptor on my model that returns properties with different names, presumably from attributes on the model itself - at least this would be usable.
Anyway, I was hoping someone had already done this?
Writing your own model binder is overkill but it's the way to do it. The binding in MVC uses reflection so you need a 1:1 match.
The other way would be to write a small class that has your fields in it that look like you want them to look and then bind the view to that.
Then in your controller you can grab those values the normal binding way and then transfer those (nice) looking fields to the other model you have.

Resources