dimanche 20 novembre 2022

Copy EF Core entity property proxy using reflection

I am trying to make a duplicate of an EF Core entity and then store it in the database. One of the tasks is copying all writable properties. Since I have to make duplicates of many entity types, I am using reflection to copy all properties and not forgetting new ones in the future.


public abstract class BaseEntity
{
    public void CopyAllWriteablePropertiesTo(BaseEntity destination)
    {
        Guard.ArgumentNotNull(destination, nameof(destination));

        if (destination.GetUnproxiedTypeName() != this.GetUnproxiedTypeName())
            throw new ApplicationException("Not same type");
    
        var properties = this.GetType().GetProperties();
        foreach (var property in properties)
        {
            if (property.Name == nameof(Id))
            {
                continue;
            }
    
            if (property.CanWrite)
            {
                Type memberType = property.PropertyType;
    
                try
                {
                    var propValue = property.GetValue(this);
                    var originalType = propValue.GetType();
                    
                                        //PROBLEMS START HERE
                    Convert.ChangeType(propValue, memberType);      
                    var convertedType = propValue.GetType();
                    property.SetValue(destination, propValue);
                }
                catch (Exception ex)
                {
                    throw new ApplicationException(ex, $"Error copying {property.Name} at object {this}");
                }
            }
        }
    }

}

With primitive types (string, int...) the process works well, but my entities have references to other entities.

I am using Lazy Loading, so when I read a property of, say DerivedEntity class,


var propValue = property.GetValue(this);

returns a proxy DerivedEntityProxy.

If I try to assign it with


property.SetValue(destination, propValue);

I get an error since types do not match ( setting a proxy object value for a raw entity).


System.Reflection.TargetException: Object does not match target type.

If before assigning I try to cast the proxy to the underlying object, I get an exception


{"Object must implement IConvertible."}

Is there a way to do this?





Aucun commentaire:

Enregistrer un commentaire