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