KevinUK
KevinUK

Reputation: 5143

Map a flat structure to an object with AutoMapper?

The data being returned from a stored procedure has 3 columns of repeating data:

Name | Address | PhoneNumber | UniqueCol1 | UniqueCol2

Ideally I want my model to show that there is repeated data by only storing the values once and have a collection of the unique data.

public class MyViewModel
{
  public string Name {get;set;}
  public string Address {get;set;}
  public string PhoneNumber {get;set;}
  public List<MyModel> UniqueData {get;set;}

  public class MyModel
  {
    public string UniqueCol1 {get;set;}
    public string UniqueCol2 {get;set;}
  }
}

This means I want to map a collection of results to a single object of MyViewModel:

return Mapper.Map<List<StoredProcedureObject>, MyViewModel>(result);

This is where I get my error as I assume I have some configuration that I need to do:

Mapping types:
List`1 -> MyViewModel

Any ideas on the missing step to get this to work?

Upvotes: 3

Views: 708

Answers (1)

Obl Tobl
Obl Tobl

Reputation: 5684

Automapper is only able to flatten your structure into something simpler. But it's not possible to map a simple class to something more specific.

I would suggest to take only the first entry in your table to fill your base fields like Name, Address, PhoneNumber and iterate over your results to fill your UniqueData List.
I don't see an easier way, because with each possible mapping and without using seperate loops you will get your base data multiple times.

If you don't mind to use another tool, maybe you will have a look at ValueInjecter. I heard you can use this tool for two-way-mappings.

Upvotes: 1

Related Questions