首页 > 解决方案 > 使用反射将属性设置为其类型的代理对象

问题描述

我正在尝试在属性上使用 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 类型的属性。

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

标签: c#reflectionentity-framework-core

解决方案


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

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


推荐阅读