使用反射将属性设置为其类型的代理对象

时间:2019-05-16 19:52:34

标签: c# reflection entity-framework-core

我正在尝试在属性上使用PropertyInfo.SetValue()。

我使用PropertyInfo.GetValue()从同一个属性中获得了值

该属性的类型为 MyObject

当我尝试使用SetValue时,出现异常:“对象与目标类型不匹配。”。原因是我通过GetValue()获得的值具有 MyObjectProxy 的运行时类型,该类型继承自 MyObject

我无法将类型为 MyObjectProxy 的对象分配给 MyObject 属性,并且还没有找到一种方法。

但是EF Core以某种方式做到了,所以我也应该能够做到吗?

//Each object that implements IProfileKey is an entity with a foreign key of myObject
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();

背景是我试图在EF Core中更改我的一个对象的主键。为此,我需要删除试图更改的对象,然后更改密钥并再次添加。

现在该对象还有其他引用它的对象,因此我也需要更改其键。所有其他这些对象都是我的主对象中IProfileKey类型的属性。

所以我的想法是使用泛型来自动查找和更新这些属性。

1 个答案:

答案 0 :(得分:0)

所以我没有弄清楚如何将MyObjectProxy对象分配给MyObject属性。

但是在更改主键时,我以为我必须重新分配同样更改的导航属性,但事实并非如此,因此我不必将MyObjectProxy对象分配给MyObject属性。