views:

60

answers:

1

Let's say I have the following entity:

public class Store
{
    public List<Product> Products { get; set; }
    public List<Employee> Employees { get; set; }
    public List<Camera> Cameras { get; set; }
}

In other words, a Store that has Products, Employees, and security Cameras. I want to convert this Store to a StoreDTO:

public class StoreDTO
{
    public List<int> ProductIds { get; set; }
    public List<int> EmployeeIds { get; set; }
    public List<int> CameraIds { get; set; }
}

In other words, the StoreDTO will only have the entity IDs.

Right now, I'm using this code to set up AutoMapper:

Mapper.CreateMap<Product, int>().ConvertUsing(x => x.Id);
Mapper.CreateMap<Employee, int>().ConvertUsing(x => x.Id);
Mapper.CreateMap<Camera, int>().ConvertUsing(x => x.Id);

As you can see, it's a lot of boilerplate code. Is there any way to configure AutoMapper to automatically convert all collections of reference types to collections of integers?

A: 

We do this with a bit of LINQ over reflection. You can use LINQ to query all types that derive from some base class of Product, Employee and Camera. Next, loop through those types calling the CreateMap and ConvertUsing methods.

There's no type scanning to speak of which is why things like this aren't really there. But it's not too bad to do your own type scanning as needed.

Jimmy Bogard
Thanks. In the end, I realized that it would take more work to write the reflection code than it would be to just explicitly map a few classes.
Daniel T.