How to use Automapper to construct object without default constructor

前端 未结 2 428
栀梦
栀梦 2020-12-10 02:02

My objects don\'t have a default constructor, they all require a signature of

new Entity(int recordid);

I added the following line:

2条回答
  •  -上瘾入骨i
    2020-12-10 02:56

    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()
                .ConstructUsing(source => new Target(source.RecordId));
    
            var src = new Source
            {
                RecordId = 5,
                Foo = "foo",
                Bar = "bar"
            };
            var dest = Mapper.Map(src);
            Console.WriteLine(dest.RecordId);
            Console.WriteLine(dest.Foo);
            Console.WriteLine(dest.Bar);
        }
    }
    

提交回复
热议问题