21

My objects don't have a default constructor, they all require a signature of

new Entity(int recordid);

I added the following line:

Mapper.CreateMap<EntityDTO, Entity>().ConvertUsing(s => new Entity(s.RecordId));

This fixes the problem where Automapper is expecting a default constructor, however the only element that is mapped is the record id.

How do I get it to pick up on it's normal mapping? How to get all the properties of the entities to be mapped without having to manually map the properties?

Richard Garside
  • 87,839
  • 11
  • 80
  • 93
Omnia9
  • 1,563
  • 4
  • 14
  • 39
  • Where does RecordId come from? The EntityDTO? If so, the latest version of AutoMapper found at AutoMapper.org supports mapping constructor arguments, which might help you here. – Jimmy Bogard Aug 25 '11 at 15:46
  • 1
    You need to use ConstructUsing. Look at [this answer][1] for details [1]: http://stackoverflow.com/questions/2239143/automapper-how-to-map-to-constructor-parameters-instead-of-property-setters – boca Aug 25 '11 at 15:51

2 Answers2

39

You could use ConstructUsing instead of ConvertUsing. Here's a demo:

using System;
using AutoMapper;

public class Source
{
    public int RecordId { get; set; }
    public string Foo { get; set; }
    public string Bar { get; set; }
}

public class Target
{
    public Target(int recordid)
    {
        RecordId = recordid;
    }

    public int RecordId { get; set; }
    public string Foo { get; set; }
    public string Bar { get; set; }
}


class Program
{
    static void Main()
    {
        Mapper
            .CreateMap<Source, Target>()
            .ConstructUsing(source => new Target(source.RecordId));

        var src = new Source
        {
            RecordId = 5,
            Foo = "foo",
            Bar = "bar"
        };
        var dest = Mapper.Map<Source, Target>(src);
        Console.WriteLine(dest.RecordId);
        Console.WriteLine(dest.Foo);
        Console.WriteLine(dest.Bar);
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • The ConvertUsing gives more flexibility when it comes to map from the viewmodel to model. Is there any way that I could use ConstructUsing with ConvertUsing? I would like to just map a few properties when mapping from viewModel to model with a constructor but when mapping from model to view model all properties should be mapped. – akd Jan 15 '17 at 03:29
  • Is there a way to make it more generic? Usecase: Convert from parent to child and whatever fields doent exist in parent, pass them as null in child – user1324887 Aug 28 '20 at 21:58
8

Try

Mapper.CreateMap<EntityDTO, Entity>().ConstructUsing(s => new Entity(s.RecordId));
CassOnMars
  • 6,153
  • 2
  • 32
  • 47