markp3rry
markp3rry

Reputation: 734

Merge data from base class into derived class

I have a class structure like this:

Spatial --> ServiceRequest --> ServiceRequestSystemX

I have written a method to return a list of ServiceRequestSystemX. The data is held separately to where the Spatial information is stored. So each time I create a new object of type ServiceRequestSystemX I make a call to a different interface to return the Spatial object for that service request.

Now because ServiceRequestSystemX is ultimately derived from Spatial, is there a quick way that I can merge my Spatial object into my ServiceRequestSystemX object without just having to do:

ServiceRequestSystemX.X_Coordinate = Spatial.X_Coordinate;

which I find tedious and unnecessary.

Upvotes: 1

Views: 746

Answers (2)

Rob Hardy
Rob Hardy

Reputation: 1821

Based on your comments in my first answer, you could try using reflection to merge the two objects together. But I would call this a dirty hack.

public static class ExtensionMethods
{
    public static TEntity CopyTo<TEntity>(this TEntity OriginalEntity, TEntity NewEntity)
    {
        PropertyInfo[] oProperties = OriginalEntity.GetType().GetProperties();

        foreach (PropertyInfo CurrentProperty in oProperties.Where(p => p.CanWrite))
        {
            if (CurrentProperty.GetValue(NewEntity, null) != null)
            {
                CurrentProperty.SetValue(OriginalEntity, CurrentProperty.GetValue(NewEntity, null), null);
            }
        }

        return OriginalEntity;
    }
}

This code taken from another post found here.

Upvotes: 0

Rob Hardy
Rob Hardy

Reputation: 1821

As a derived type, the ServiceRequestSystemX will already expose base members exposed by the Spatial class.

Upvotes: 4

Related Questions