Search code examples
.netarchitectureautomapperautomapping

Complex DAL -> BL mappings using AutoMapper


I'm considering to use AutoMapper in the upcoming project and trying to find possible "bottlenecks". At the moment the most complex case i can imagine is the following: A domain class which is represented by 3 (for example) tables in the database (my data access layer is LINQ to SQL). To build an instance of the class i need to perform 3 queries:

  1. Select by ID from table A (1 row, goes directly to Class properties)
  2. Select by ID from table B (0..1 rows, goes to optional Class.Code property)
  3. Select by ID from table C (0..N rows, goes to Class.Parameters collection)

And i'm not sure how to configure the mapping. Here are the options i considered:

  1. Perform 3 queries and map Tuple<A,B,C> -> Class
  2. Combine queries 1 and 2 using outer join (more effective). But what do i do with anonymous type?
  3. Inject datacontext into the mapping, define A -> Class mapping and let the type converters do the job?

None looks like a win. What would you suggest?

Edit: Well, such complex cases is quite rare (10-20%) and i can do them manually and the rest 80-90% with AutoMapper just fine. But i'd like to know if AutoMapper is not designed for such strategies or i'm missing something important.


Solution

  • Your question is difficult to answer because how and where a domain object get its data is not the concern of AutoMapper. From the AutoMapper documentation:

    AutoMapper is geared towards model projection scenarios to flatten complex object models to DTOs and other simple objects, whose design is better suited for serialization, communication, messaging, or simply an anti-corruption layer between the domain and application layer.

    However, this doesn't mean that your use of AutoMapper shouldn't factor into the thought process behind your domain objects. As an example lazy loading springs to mind. For instance in your case if you used lazy loading on the Class.Parameters property, but then ran that property through AutoMapper the data would always be loaded. That's why it's important to stick to the rule of one model per view.

    Jimmy Bogard one of the creators of AutoMapper discusses his vision for what AutoMapper is in AutoMapper: the Object-Object Mapper. I wish I could link directly to it but in a comment reply on the aforementioned post Bogard states:

    That's something we've looked at for a while (two-way binding), but in the end, we found that there was just too much business validation in an Update.

    Instead, we formed other patterns around updating a model from a message/form. See Code Camp Server source for more details.

    As indicated you can find heavy use of AutoMapper in the source for CodeCampServer. A simplified version of the CodeCampServer code can be found in the source code provided with ASP.NET MVC 2 in Action.