如何使用Automapper来构造对象没有默认构造函数 [英] How to use Automapper to construct object without default constructor

查看:1165
本文介绍了如何使用Automapper来构造对象没有默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这可修复Automapper期待一个默认的构造函数的问题,但是所映射的唯一因素是记录ID。

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?

推荐答案

您可以使用 ConstructUsing 而不是 ConvertUsing 。下面是一个演示:

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

这篇关于如何使用Automapper来构造对象没有默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆