如何使用Automapper构造没有默认构造函数的对象
我的对象没有默认构造函数,它们都需要签名
new Entity(int recordid);
我添加了以下行:
Mapper.CreateMap().ConvertUsing(s => new Entity(s.RecordId));
这解决了Automapper期望默认构造函数的问题,但是映射的唯一元素是记录ID。
如何让它了解它的正常映射? 如何在不必手动映射属性的情况下获取要映射的实体的所有属性?
您可以使用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
尝试
Mapper.CreateMap().ConstructUsing(s => new Entity(s.RecordId));