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

Arn*_*j65 16 .net c# automapper

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

new Entity(int recordid);
Run Code Online (Sandbox Code Playgroud)

我添加了以下行:

Mapper.CreateMap<EntityDTO, Entity>().ConvertUsing(s => new Entity(s.RecordId));
Run Code Online (Sandbox Code Playgroud)

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

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

Dar*_*rov 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);
    }
}
Run Code Online (Sandbox Code Playgroud)


doc*_*ess 8

尝试

Mapper.CreateMap<EntityDTO, Entity>().ConstructUsing(s => new Entity(s.RecordId));
Run Code Online (Sandbox Code Playgroud)