c# - .NET 反射 : how to get properties defined on partial class

标签 c# .net linq entity-framework reflection

我使用 .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");

property1property2 都返回了属性。

[编辑]

试过你的代码,经过小的修改它可以工作:

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/

相关文章:

.net - 将文本应用于第三方控件时的编程问题

c# - List<List<string>> 上的 Linq 计数组

c# - 使用多个参数调用控件时参数计数不匹配

c# - Click 事件的 XAML 参数

c# - 将实体转换为 View 模型以与 Web API 一起使用

c# - 如何在隐藏字段中存储和接收字节数组?

.net - 在 WPF 中拖动图像

C# 判断字符串数组中的某个元素是否在任意位置包含给定的字符串

c# - 使用 2 个 from 子句重写 linq-to-sql 查询以连接

vb.net - 帮助使用 Linq 和泛型。在查询中使用 GetValue