HaBo
HaBo

Reputation: 14297

Cast one type to another

class childType: MainType{}

MainType mObj = GetData();

childType cObj = (childType)mObj;

How can I cast above

childType cObj = (childType)mObj;

I get this error:

Unable to cast object of type 'System.Data.Entity.DynamicProxies.MainType_F04DC499C53D433B05ABEDEE7191583DB11728F68B18671613EF0E5AC158DD0D' to type 'ChildType'.

Upvotes: 1

Views: 634

Answers (3)

Yusuf Uzun
Yusuf Uzun

Reputation: 1511

This is because of EF5 dynamic proxies. Even if you want to cast

mObj = (MainType)cObj; 

like this, you wouldn't. Because dynaimc proxy creates runtime concrete types. So you can disable dynamic proxy or inject values explicitly. If you close dynamic proxy you cannot use Lazy Loading neither.

So my advice simply use ValueInjecter. It has extension methods for object. And you can write something like this :

//this is not dynamic proxy object.
childType cObj = new childType().InjectFrom(mObj) as childType;

//or

// but this comes from dynamic proxy.
childType cObj = DbSet<childType>.Create().InjectFrom(mObj) as childType;

And you will see all hundreds of properties are injected by your mObj properties.

Upvotes: 1

evanmcdonnal
evanmcdonnal

Reputation: 48096

The cast you're attempting isn't actually possible. If you had something like;

 MainObj myObj = new ChildObj();
 ChildObj cObj = (ChildObj)myObj;

it would work. You could also cast a child object to it's parent class (specific to general) but you can't go from general to specific because being a MainObj is not sufficient for being a ChildObj (being a ChildObj is sufficent for being a MainObj, it has everything MainObj has plus more).

You can either make a constructor for ChildObj that takes in a MainObj and returns a ChildObj with default values for it's other properties or just reconsider your design. You should be asking the question of "Why would I cast a parent into a child?"

The opposite makes sense because you may have 5 classes that inherit from a common base class and override methods within it. You want some other method to be able to accept all five and invoke their specific functionality. This is accomplished via inheritance or by implementing an interface. Going from the general to the specific however, doesn't make sense nearly as often.

Upvotes: 1

Mathew Thompson
Mathew Thompson

Reputation: 56429

You should have a constructor in your child type that takes an instance of the main type.

Then you can do:

childType cObj = new childType(mObj);

Given this constructor on childType:

public childType(MainType obj)
{
    //set child type properties here
}

Upvotes: 4

Related Questions