Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy values from object1 to object2 using AutoMapper

Tags:

c#

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.

like image 806
Dilhan Jayathilake Avatar asked Oct 24 '25 04:10

Dilhan Jayathilake


1 Answers

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.

like image 176
Roy Sanchez Avatar answered Oct 26 '25 19:10

Roy Sanchez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!