Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET reflection: how to get properties defined on partial class

I use the .NET Entity Framework. I want to copy properties from one EntityObject to another. But System.Type.GetProperties() does not seem to return the properties defined on the partial class.

Code:

In XXX.edmx/ XXX.Designer.cs generated by Visual Studio, I have class MyTable:

public partial class MyTable: EntityObject{..}

I want to add some properties to MyTable class, so I add file XXX.Manual.cs:

public partial class MyTable: EntityObject{
    public string myProp{get;set;}
}

But myTableObj.GetType().GetProperties() does not contain myProp!!!

How can I get myProp using reflection?

[EDIT] I want to comment to Alex answer but don't know why the code section is not formated.

Yes, this is very strange. I use this code to copy properties from Entity to another obj:

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);

Of couse myTableObj & anotherTableObj is of type MyTable.

When debug into the CopyTo method, VS show that Entity & another is of type MyTable & I can see Entity.myProp, another.myProp

But the Property var in foreach statement simply don't loop to myProp property!

[EDIT] Sorry. The code above (CopyTo method) is copy from diamandiev's answer for another question

But his code is wrong: The "break" statement must be replace by "continue" :D

like image 347
Bùi Việt Thành Avatar asked Feb 24 '23 19:02

Bùi Việt Thành


1 Answers

First of all partial classes is just how source code is split. It does not affect the compiled assembly.

It is likely that you don't see myProp property because myTableObj is not of type MyTable.

Try this:

var property = typeof(MyTable).GetProperty("myProp");

[EDIT]

Just checked:

EntityObject x = new MyTable();

var property1 = typeof(MyTable).GetProperty("myProp");
var property2 = x.GetType().GetProperty("myProp");

Both property1 and property2 returned the property.

[EDIT]

Tried your code, it worked after small modification:

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);
    }
}
like image 179
Alex Aza Avatar answered Mar 06 '23 02:03

Alex Aza