Say I have one class
that looks like this:
public class Person
{
public string Name {get; set;}
public int Number {get; set;}
}
And another that looks like this:
public class Dog
{
public string Name {get; set;}
public int Number {get; set;}
}
They are two different classes, but they happen to have the exact same elements (a string called Name
and an int called Number
)
Is there an easy way in C# to, say, if I had an instance of Person
to then create an instance of Dog
with the same Name
and Number
?
For example if I had:
Person person = new Person();
person.Name = "George";
person.Number = 1;
I know I can't simply go:
Dog dog = person;
Because they are two different types. But is there a way in C# to check "oh, if they have the same element, set the same elements of Dog
to equal that of Person
.
But I feel there has to be an easier way than doing something like:
dog.Name = person.Name;
dog.Number = person.Number;
Especially if the class has a LOT of elements. Also if anyone is wondering, these two different classes are in two different pieces of the API, so I can't simply make them related either.
You can use AutoMapper:
Then you can easily:
Just don't forget to install
AutoMapper
first from the package manager console as mentioned in the reference:Then type the following command:
If you don't work with big generic list, you can do it using LinQ.
It's easy to remember, and you can filter data previously.
Install
AutoMapper
package in your project.As a best practice (for web applications) you can create new class (should derives from
Profile
) in yourApp_Start
folder, that will contain all your mappings for your project.Then Initialize your mapping inside the
Application_Start
method inGlobal.asax
You can now use the mappings that you have created
An object oriented approach.
This will allow the following: