0

Since the Entity Framework creates proxy instead of providing the "original" entity classes, how do you cast a parent class to a child class? This does not work "the normal way" because the automatically created proxy classes don't use the inheritance structure of the original entity classes.

Turning off the proxy-creation feature is not an option for me.

Any help is welcome, thanks!

Cleo
  • 93
  • 1
  • 2
  • 9
  • Can you provide some example code to illustrate what is failing and the error you're receiving? I've never had any issues casting proxy objects to their non-proxy counterpart. – w.brian Apr 11 '13 at 16:29
  • Well I want to cast a parent-proxy-object to a child-object. Since I don't know the corresponding child-proxy-class, I have to use the original child class. This cast results in an InvalidCastException. – Cleo Apr 11 '13 at 16:42
  • The inheritance chain is still intact. You don't need to figure out what the "child" proxy class is. Chances are you're doing something erroneous, but without example code it's going to be hard to tell exactly what you're doing wrong. – w.brian Apr 11 '13 at 16:47

1 Answers1

0

How do you cast a parent class to a child class?

You can only cast a parent to a child if the actual runtime type is a child. That's true for non-proxies and proxies because a proxy of a child derives from a child, hence it is a child. A proxy of a parent is not a child, so you can't cast it to a child, neither can you cast a parent to a child.

For example (using DbContext API):

public class Parent { ... }
public class Child : Parent { ... }

Then both the following casts will work:

Parent parent1 = context.Parents.Create<Child>(); // proxy
Parent parent2 = new Child();                     // non-proxy

Child child1 = (Child)parent1; // works
Child child2 = (Child)parent2; // works

And both the following won't work:

Parent parent1 = context.Parents.Create<Parent>(); // proxy
Parent parent2 = new Parent();                     // non-proxy

Child child1 = (Child)parent1; // InvalidCastException
Child child2 = (Child)parent2; // InvalidCastException

Both casts work "the normal way".

Slauma
  • 175,098
  • 59
  • 401
  • 420
  • Ok this explains my problem. What I wanted to to was: Child child2 = (Child)parent2; // InvalidCastException This kind of complicates things because you can't just create the parent and assign values and then check if its a child and assign the child's fields. – Cleo Apr 12 '13 at 09:03
  • @Cleo: Well, you could use the **is** operator to check if it's a child: `if (parent1 is Child) ...` – Slauma Apr 12 '13 at 11:50