Copy values from object1 to object2 using AutoMapper

I have Person class

public class Person
{
   public int PersonID { get; set; }
   public string FullName { get; set; }
   public int InternalValue { get; set; }
}

And, this is my DTO class

public class PersonDto
{
   public int person_id { get; set; }
   public string full_name { get; set; }
}

I am using AutoMapper and AutoMapper.Attributes to perform the Mappings as shown as bellow;

[MapsTo(typeof(Person))]
public class PersonDto
{
   [MapsToProperty(typeof(Person), "FullName")]
   public int full_name { get; set; }
}

I have an API which accepts PersonDto and save into the database using Entity Framework. Note that the InternalValue is not available in the DTO class which is a secret value :).

My question is; Is there any possibility to copy the values from a PersonDto object to Person object using AutoMapper? I have found some similar questions but couldn't found a strait answer.

Thanks in advance and your help would be greatly appreciated.


To Map from PersonDto to Person you need to configure the attribute to allow reverse configuration.

Change the attribute to look like this:

[MapsTo(typeof(Person), ReverseMap = true)]

this will allow to call AutoMapper for PersonDto -> Person, to see more you can check the README of the project here.


为了扩展前面的答案,如果您通过automapper congif文件或code进行映射,则可以这样做:

AutoMapper.Mapper.CreateMap<PersonDto,Person>().ReverseMap();
链接地址: http://www.djcxy.com/p/6384.html

上一篇: 多语言数据库与实体框架4指导

下一篇: 使用AutoMapper将object1的值复制到object2