jeudi 16 mai 2019

Setting a property to a proxy-object of its type using reflection

I am trying to use PropertyInfo.SetValue() on a Property.

I got the Value from that same Property using PropertyInfo.GetValue()

The property is of type MyObject.

When I try to use SetValue I get an exception: "Object does not match target type.". The reason beeing that the Value I got through GetValue() has a runtime type of MyObjectProxy, which inherits from MyObject.

I cannot assign an object of type MyObjectProxy to a MyObject Property and havent found a way to do so.

But EF Core did it somehow, so shouldnt I be able to do it as well?

List<PropertyInfo> myProperties = GetPropertiesOfType(typeof(IProfileKey));

//Get values from all properties as IProfileKey
List<IProfileKey> myValues = myProperties.Select(x => (IProfileKey)x.GetValue(myObject)).ToList(); 
myProperty.GetValue(myObject);

MyContext.Remove(ofObject);
MyContext.SaveChanges();

UpdatePrimaryKeys(myValues);

foreach(int i = 0; i < myProperties.Count; i++)
{
    //Heres the problem
    //myProperties[i] is of type MyObject, while myValues[i] is of type MyObjectProxy
    myProperties[i].SetValue(myObject, myValues[i]); 

}

MyContext.Add(myObject);
MyContext.SaveChanges();

The background is that I am trying to change the primary key of one of my objects in EF Core. For that I need to Delete the Object im trying to change, then change the key and add it again.

Now that object also has other objects referencing it, so I need to change their Keys as well. All these other objects are properties of type IProfileKey in my main object.

So my idea was to use generics to automatically find and update these properties.





Aucun commentaire:

Enregistrer un commentaire