Friday, July 31, 2009

A Little Sugar for Your MVC

I've recently started using two new tools that have made ASP.NET MVC development just a little sweeter.

AutoMapper is a convention based object-to-object mapper. This sounds scarier than what it is. This just means instead of this:

Var instance1 = new MyModel();
  instance1.Property1 = instance2.Property1;
  instance1.Property2 = instance2.Property2;
  instance1.Property3 = instance2.Property3;

you can do this:

Mapper.CreateMap<MyModel,MyModel>(); //typically at a ‘global’ level like Global.asax
   Mapper.Map(instance1, instance2);

There is a perf hit, since it's having to do a little reflection to make this magic happen, but for many cases, this perf hit is negligible and acceptable.  It gets a little more complex, in that you can define type converters and other means to handle special cases or conversions from one type to another. There are examples on the site. The main place this is useful in a simple MVC business app is in updates where you typically go get an existing record from the db and then do that right-to-left code to set some properties before calling SubmitChanges().

T4 is a code generation tool that’s been built into VS since 2005. T4MVC is a T4 template to give you some syntax sugar in MVC. I've blogged about this before, but it's come a long way since then, including a link from the official MVC site in CodePlex.  It looks over your application, and generates code to help you do common stuff a little cleaner , more strongly-typed way. For example, instead of this:

public ActionResult MyAction(){
    return View(“SomeView”);

you can and should do this:

public ActionResult MyAction(){
     return View(Views.SomeView);

And instead of this:

<%=Html.ActionLink(“Text”, “MyAction”, new{id=someValue)%>

You can and should do this:

<%=Html.ActionLink(“Text”, MVC.MyController.MyAction(someValue))%>

The main benefit being, if your controller or action changes, then the 2nd examples will break the build, whereas the 1st examples you won’t catch until runtime.

No comments: