Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Automapper to construct object without default constructor

Tags:

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?

like image 266
Omnia9 Avatar asked Aug 25 '11 14:08

Omnia9


1 Answers

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);
    }
}
like image 106
Darin Dimitrov Avatar answered Oct 02 '22 09:10

Darin Dimitrov