Posts for the tag: AutoMapper

Jun
4
2012

Building a Blog Redux - Mapping View Models to Entities Using AutoMapper (Part 6)

This is the sixth post in a series of posts about how I went about building my blogging application.

  1. Building a Blog Redux - Why Torture Myself (Part 1)
  2. Building a Blog Redux - The tools for the trade (Part 2)
  3. Building a Blog Redux - Entity Framework Code First (Part 3)
  4. Building a Blog Redux - Web fonts with @font-face and CSS3 (Part 4)
  5. Building a Blog Redux - Goodreads feed using Backbone.js (Part 5)

In the basic building parts of a MVC web application there are the models, the views, and the controller. The models represent the data that will be placed in the view. The controller is the guy that goes and gets the data (the model) and puts it in the view. Then finally, view is responsible for presenting the data to the user. If the data schema is simple, you could use an ORM like Entity Framework, nHibernate, LINQ, or go old school data-access-layer and pass the entity that represents a SQL table directly to the view and display it on the page.

However, as views get more complicated, the data in the entities needs to be manipulated and changed before you can display it in a view. Often times, the views have fields that are not needed in an entity or vice-versa. You could end up with bloated entities that have a lot of properties that are not mapped to any field in a database. Back in the days of yore, we might resorted to creating stored procedures to manipulate the data to return properties we needed, but then the next guy to come along and work who wanted to make changes to that application learned quickly that this was a very bad idea.

My Approach

My MVC applications are really MVCS applications. That is, I typically add a service layer to my applications between the controller and the models, where I try and keep the lion share of my business (domain) logic. Also, instead of having entities display on the page, I create classes that represent a view models and then I map the entities to the view model which then get sent to the views. This mapping takes place in my new service layer that I just created.

Doing this gives keeps my entities clean and provides for a better separation of concerns between my database and my front end views. However, mapping entities to views and vice-versa can be a challenge especially as your application grows in both size and complexity. It can also be quite tedious, and makes for a laborious day of coding.

Enter AutoMapper

So to handle all my mappings, I use AutoMapper. Here is what AutoMapper is in their own words.

"AutoMapper is an object-object mapper. Object-object mapping works by transforming an input object of one type into an output object of a different type. What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B. As long as type B follows AutoMapper's established convention, almost zero configuration is needed to map two types."

Configuring AutoMapper.

Before mapping an entity object to a view model object, I need to tell AutoMapper the details about these mappings. Most times, the defaults were used, which by convention, is if object A has property with the same name as object B then those to fields will be automatically mapped. If object A has a property that object B doesn't have, then I can ignore it, or do something custom to account for that field. In an MVC web application, these configuration steps are done when the application starts.

In my Application_Start event in the global.asax.cs file, I have the following code.

Bootstrapper.RegisterMappings();

Inside this function, I register a profile for each of my mappings. These profile class is what tells AutoMapper the details of each of the mappings.

 public static void RegisterMappings()
        {
            Mapper.Initialize(x =>
                                  {
                                      x.AddProfile(new UserMapperProfile());
                                      x.AddProfile(new UserRoleMapperProfile());
                                      x.AddProfile(new BlogSiteMapperProfile());
                                      x.AddProfile(new PostMapperProfile());
                                      x.AddProfile(new SettingMappingProfile());
                                      x.AddProfile(new PingServiceMappingProfile());
                                  });;
        }

Here is an example of a simple configuration.

public class SettingMappingProfile : Profile
    {
         public const string ViewModel = "SettingProfile";
 
        public override string ProfileName
        {
            get { return ViewModel; }
        }
 
        protected override void Configure()
        {
            CreateMap<SettingSettingViewModel>();
            CreateMap<SettingViewModelSetting>();
        }
    }

In this case, I have a maping from the entity to the view and also from the view to the entity. Also, notice that my mapping class is inheriting from the Profile base class which is doing all of the magic and taking care of all of my mappings.

Where I have mappings that I need to ignore a field, I can use the Ignore option.

CreateMap<BlogSiteViewModelBlog>()
                .ForMember(dest => dest.Id, opt => opt.MapFrom(x => x.BlogId))
                ;

If I have a property that is itself an object and I want to map the Id property to its Is property and then instantiate the object, I could do the following.

CreateMap<HtmlFragmentViewModelHtmlFragment>()
                .ForMember(dest => dest.Blogs, opt => opt.Ignore())
                .ForMember(dest => dest.Location,
                           opt => opt.MapFrom(x => new HtmlFragmentLocation {Id = Convert.ToInt32( x.SelectedLocationId)}));
                ;

In some cases, I have property that I want to do special things with. In those cases, I can use what's called a value resolver. For example for my tags, I want to store them in the database as a collection; however, I want to display them on the page as comma delimited property. Here's how I can do this using AutoMapper.

First specify in the configuration to use a custom ValueResolver.

.ForMember(dest => dest.TagListCommaDelimited, opt => opt.ResolveUsing<TagListToDelimiterResolver>())

Then in the derived value resolver class, add the code to handle the list to delimiter functionality.

    public class TagListToDelimiterResolver : ValueResolver<Poststring>
    {
        protected override string ResolveCore(Post source)
        {
            if (source == nullreturn string.Empty;
            if (source.Tags == nullreturn string.Empty;
            string tagDelimited = source.Tags.Aggregate(string.Empty,
                                                        (current, tag) => current + string.Format("{0},", tag.TagName));
 
            return !string.IsNullOrEmpty(tagDelimited)
                       ? tagDelimited.Substring(0, tagDelimited.Length - 1)
                       : tagDelimited;
        }
    }

Testing

One of the things I like about AutoMapper is that it has an assert routine you can use to set up tests to test that your configuration works. When a test fails, the assert function does a good job of letting you know where the problem lies and which property is have an issue. Leaning on these mapping unit tests save me lots of time configuring my mappings, and I pretty much knew that if my tests were passing, then my web application would handle the mappings without any issues.

        [TestMethod]
        public void Should_be_able_to_configure_user_profile_to_view()
        {
            Bootstrapper.RegisterMappings();
            Mapper.AssertConfigurationIsValid();
        }

Mapping

Once the configurations are in place, the Mapper.Map function can be called and the views will be mapped to entities and entities map to views. Typically, I like to add some further abstraction and place these tasks in there own classes. This way, I can mock the results in a tests and add some additional customization if needed.  It also makes the mappings a little more maintainable.

public class PostMappingService : IPostMappingService
    {
        public Post MapToEntity(PostViewModel viewModel)
        {
            return Mapper.Map<PostViewModelPost>(viewModel);
        }
 
        public PostViewModel MapToView(Post entity)
        {
            return Mapper.Map<PostPostViewModel>(entity);
        }
    }

Conclusion

Hope this helps. As usual, you can see all of the code at GitHub.

 

 

 

Apr
4
2012

Building a Blog Redux -ASP.NET MVC, Razor, & Other Tools (Part 2)

This is the second post in a series of posts about how I went about building my blogging application.

  1. Building a Blog Redux - Why Torture Myself (Part 1)

In this post, I want to briefly discuss some of the tools, frameworks, best practices I used to build this blog site. I'll go into more details in future posts but for now I am just going to discuss the project setup.

ASP.Net MVC

The website itself is an ASP.Net MVC 3 project using the Razor View Engine. I also have a core project and a unit test project within the solution.

I am using the Razor View Engine, and although I still think that the Spark View Engine did some things better like adding repeaters right with the markup, I think Razor is a pretty good and with the backing of Microsoft as well as a large development community behind it, it should continue to keep getting better.

So with that said let;s take a quick look. Below is the partial view for posts.

@model AviBlog.Core.ViewModel.PostViewModel
 
<article>
    <div  class="post-heading">
        @Html.Partial("_PublishDate", Model.DatePublished)
        <h2>@Html.ActionLink(Model.Title, "Post""Posts", 
            new {id = Model.Slug}, new {@class = "post-title-link"})</h2>
    </div>
    <div>@Html.Raw(Model.PostContent) </div>
    <div class="post-meta-info">
        <ul>        
            @if (Model.DatePublished.HasValue)
            {
                <li class="align-left">Published on: @Model.DatePublished.Value.ToLongDateString()</li>
            }
        </ul>
    </div>
</article>

One of the nice things about Razor markup is that it does a good job of understanding where the server-side code ends and the HTML resumes. Even when you server code wraps on to another line, like it does above, it still transitions back to the HTML smoothly. This make the markup pretty clean and readable.

Another thing to notice is that Razor has the HTML encoding logic is reveresed from the Web Forms approach. In order to render HTML markup, I needed to use the HTML helper function "Raw", otherwise my content would be rendered as text.

Dependency Injection and Inversion of Control Using StructureMap

As with all MVC sites that I build, I always incorporate a strategy of Inversion Control. For more than a couple of years now, I have been exclusively using StructureMap as the framework of choice.

Dependency Injection simply means that all objects that your specified object is dependent on is injected into itself via the constructor or a getter. The most common approach seems to be through the constructor, and that is the approach that I am using as well.  Another thing to note here is that a dependent object is always specified as an interface. So when building your class your constructor would like as follows:

        private readonly IBlogSiteRepository _blogSiteRepository;
        private readonly IBlogsSiteMappingService _mappingService;
 
        public BlogSiteService(IBlogSiteRepository blogSiteRepository, IBlogsSiteMappingService mappingService)
        {
            _blogSiteRepository = blogSiteRepository;
            _mappingService = mappingService;
        }

Using this pattern in a MVC application really makes it more maintainable and easier to write unit tests for. The application is far less coupled, which is always a good thing in world of object oriented programming.

Inversion of Control states that an object should not be responsible to instantiate another object it is dependent on, but rather it should depend on a common "assembler" object that does the instantiating task for it. The specified object should not know anything "concrete" about the dependent object except for its specified interface. So essentially what happens at runtime is when an object is entered into by the program flow, it has already been handed all the dependent object it needs to complete its task.

I am using the MVC 2 setup of the StructureMap approach and not the new DependencyResolver that was shipped with MVC 3 only because, the older approach works pretty well. Its limitation is that it is only able to inject objects into MVC controller and not ActionFilters, ModelBinders, etc.; however, up until now, I have only needed it in two places outside of controllers and so that is not enough for me to change. I see there is a Nuget package for installing StructureMap as a DependencyResolver, so perhaps in the future I will switch to that approach instead.

But for now you can see a really good post of how I am implementing Structure map by Elijah Mannor.

There are several different IofC containers such as NInject, Castle Windsor, Unity, Autofac etc, but I use StructureMap mainly for one feature and that is scanning. The ability to scan all you assemblies and then map the interfaces to the concrete classes based on a "convention" is such a time saver. For example; a StructureMap scan will automatically map the interface IFoo to the concrete class Foo because the like name Foo. StructureMap assumes that IFoo and Foo belong together and thus maps them to each other. I used to use Unity, but would end up with configuration files that were several pages long and a pain to maintain. Now with StructureMap, I only have to explicitly map the exceptions (such as a class that has a different name than the interface) which in this Aviblog solution there are none. I think now at the time of the writing this post, all of the previously mention IofC containers have this feature with the exception of Unity.

Entity Framework 4.3

Entity Framework has come such a long way from its early days. I was really disappointed with its earlier releases and said so. But hats off to the Entity Framework team for listening to the community of developers and making an OR Mapper that is quite good. I built this blog application using the "Code First" approach and it worked out quite well.

In my next post in this series, I will go into further detail about how I set up Entity Framework and include some code samples.

​HTML5 and CSS3

I am using the HTML5 semantics in tags such as "header", "footer", "article" and "aside" for the first time. I am also using new CSS3 features such as rounded corners, shadows, and media queries to detect the size of the browser window.

Those of you viewing this post from an older browser will see that I haven't quite got all the symantics working, but I'll fix those issues and write a post about the experience as well.

Fonts

Who knew there were other fonts besides Verdana or Tahoma? Another big learning experience for me, so I'll write more about this in a future post.

I'll state here that I am using one of the Google Open Source Web Fonts, mainly because it was pretty simple to set up and I liked couple fonts that were on that site.

AutoMapper

When building an MVC application, its good to have a model that is specific for that view and same model being used by your database. For example, a user registration view could have a password and a re-enter password field, but you would only have a password field in the database table.

AutoMapper is a good way to separate the two models and then provide a process to map those data from your entity to your view model and vice-versa without having to write a lot of tedious code.

So with that said I am using AutoMapper to map my views to my entities, and and my entities to my views. I setup the mapping configurations on the application startup using configuration classes so I don't need to write any mapping code every time I want to map something. I'll talk more about this in a future post.

​What Else?

These are some of the big potatoes in the field, but I will also about other things like topics such as performance improvements, refactoring opportunities, SEO implementations and much more so stay tuned. I also promise to include some samples and links to good resources that I found useful and hopefully you might useful as well.

You can also checkout the code base at GitHub.