【问题标题】:Setting a property to a proxy-object of its type using reflection使用反射将属性设置为其类型的代理对象
【发布时间】:2019-05-17 15:16:31
【问题描述】:

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

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

该属性的类型为 MyObject。

当我尝试使用 SetValue 时出现异常:“对象与目标类型不匹配。”。原因在于我通过 GetValue() 获得的 Value 的运行时类型为 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# reflection entity-framework-core


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2010-10-26
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多