I’m pretty sure this is impossible, but here goes..
I have a custom class in C# called Person which has a few properties such as Age, Height etc.
I then make a new class called Employee which inherits from Person but I don’t yet add any other properties to Employee. So its basically just a Person still, except its called an Employee.
Now say I have an instance of Person called SomePerson. How can I create a new Employee instance that has all of the values it inherited from Person, set to those inside SomePerson. Like casting from a Person into an Employee.. But without me having to manually specify each and every property that needs to be set..
Something like..
Employee NewEmployee = (Employee)SomePerson;
But of course you get the error saying “Can’t convert a Person into an Employee” etc.
Is AutoMapper the only practical solution to do things like this if you say had 300 properties in the involved objects??
UPDATE:
Auto-Mapper doesn’t seem to handle my objects..
Employee SomeEmployee = EmployeeRepository.GetEmployee(SomeEmployeeID);
// Populate the ViewModel with the Person fetched from the db, ready for editing..
VMEmployee EmployeeToEdit = Mapper.Map<Employee, VMEmployee>(SomeEmployee);
// ViewModel based on Employee with Validation applied..
[MetadataType(typeof(Employee_Validation))]
public class VMEmployee : Employee
{
// Absolutely nothing here
}
where “Employee” is auto-generated by LINQ to SQL..
AutoMapper is a good solution in this case. If you’re not going to use a property mapping framework, and you’re not willing to create a copy constructor
public Employee(Person person), or an implicit/explicit conversion, how else do you expect to copy the properties across. Realistically you could1.Reflection
2.Copy Constructor
3.Implicit/Explicit Conversion
4.AutoMapper
5.Combination of 3/4:
A note on implicit/explicit conversion operators: I believe in using these you won’t be generating CLS-compliant code.
As @Mitch Wheat has already said, if you have an object with over 300 properties, I would reconsider what that object actually represents. Refactor refactor refactor.