如何使用Automapper构造没有默认构造函数的对象

时间:2011-08-25 14:36:37

标签: c# .net automapper

我的对象没有默认构造函数,它们都需要

的签名
new Entity(int recordid);

我添加了以下行:

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

这解决了Automapper期望默认构造函数的问题,但是唯一映射的元素是记录ID。

如何让它了解它的正常映射?如何在不必手动映射属性的情况下获取要映射的实体的所有属性?

2 个答案:

答案 0 :(得分:33)

您可以使用ConstructUsing代替ConvertUsing。这是一个演示:

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);
    }
}

答案 1 :(得分:8)

尝试

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