c# - 使用反射将属性设置为其类型的代理对象
问题描述
我正在尝试在属性上使用 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 类型的属性。
所以我的想法是使用泛型来自动查找和更新这些属性。
解决方案
所以我没有弄清楚如何将 MyObjectProxy 对象分配给 MyObject 属性。
但是在更改主键时,我认为我必须重新分配也更改的导航属性,但事实并非如此,所以我不必将 MyObjectProxy 对象分配给 MyObject 属性。
推荐阅读
- c - 为什么我在 Gussing 游戏中没有得到 3 次尝试?
- drupal-7 - 在 Drupal 7 ddebug_backtrace 中捕获错误堆栈
- javascript - 一般选择所有数据属性元素
- laravel - Laravel-Mediable 库不适用于 s3 存储桶
- android - 在 react-native 中处理单击和双击
- json - React JS 减少函数中的 API 调用
- java - 在方法中返回 null
- javascript - React Hook Form 和 watch() 的自定义 onChange
- ldap - 如何覆盖 WSO2 ldap/AD 的登录认证过程
- javascript - 更改 Y2mate.com 的 DOM JavaScript 的默认值