我使用 .NET Entity Framework 。我想将属性从一个 EntityObject 复制到另一个。但是 System.Type.GetProperties() 似乎没有返回在分部类上定义的属性。
代码:
在 Visual Studio 生成的 XXX.edmx/XXX.Designer.cs 中,我有 MyTable 类:
public partial class MyTable: EntityObject{..}
我想为 MyTable 类添加一些属性,所以我添加了文件 XXX.Manual.cs:
public partial class MyTable: EntityObject{
public string myProp{get;set;}
}
但是 myTableObj.GetType().GetProperties()
不包含 myProp!!!
如何使用反射获取 myProp?
[编辑] 我想对 Alex 的回答发表评论,但不知道为什么代码部分没有格式化。
是的,这很奇怪。 我使用此代码将属性从实体复制到另一个对象:
public static void CopyTo(this EntityObject Entity, EntityObject another){
var Type = Entity.GetType();
foreach (var Property in Type.GetProperties()){
...
Property.SetValue(another, Property.GetValue(Entity, null), null);
}
}
//in some other place:
myTableObj.CopyTo(anotherTableObj);
当然 myTableObj 和 anotherTableObj 是 MyTable 类型。
当调试 CopyTo 方法时,VS 显示 Entity 和另一个是 MyTable 类型,我可以看到 Entity.myProp、another.myProp
但是 foreach 语句中的 Property var 根本不会循环到 myProp 属性!
[编辑] 抱歉。上面的代码(CopyTo 方法)是从 diamandiev's answer for another question 复制的
但是他的代码是错误的:“break”语句必须用“continue”替换:D
最佳答案
首先,分部类就是源代码的分割方式。它不会影响已编译的程序集。
您可能没有看到 myProp
属性,因为 myTableObj
不是 MyTable
类型。
试试这个:
var property = typeof(MyTable).GetProperty("myProp");
[编辑]
刚刚检查:
EntityObject x = new MyTable();
var property1 = typeof(MyTable).GetProperty("myProp");
var property2 = x.GetType().GetProperty("myProp");
property1
和 property2
都返回了属性。
[编辑]
试过你的代码,经过小的修改它可以工作:
public static void CopyTo(EntityObject fromEntity, EntityObject toEntity)
{
foreach (var property in fromEntity.GetType().GetProperties())
{
if (property.GetSetMethod() == null)
continue;
var value = property.GetValue(fromEntity, null);
property.SetValue(toEntity, value, null);
}
}
关于c# - .NET 反射 : how to get properties defined on partial class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6462959/