Question

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!

Was it helpful?

Solution

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".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top