我使用 .NET 实体框架。我想将属性从一个 EntityObject 复制到另一个。但 System.Type.GetProperties() 似乎没有返回分部类上定义的属性。
Code:
在 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;}
}
But myTableObj.GetType().GetProperties()
不包含 myProp!!!
如何使用反射获取 myProp?
[EDIT]我想对 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 & another 的类型为 MyTable & 我可以看到 Entity.myProp、another.myProp
但是 foreach 语句中的 Property var 根本不循环到 myProp 属性!
[EDIT]对不起。上面的代码(CopyTo方法)是从迪亚曼迪耶夫对另一个问题的回答
但他的代码是错误的:“break”语句必须替换为“continue”:D