Entity Framework #1 –How to get the original type of an entity when dynamic proxy is enabled

If your Entity Framework context is proxy-enabled, the runtime will create a proxy instance of your entities, i.e. a dynamically generated class which inherits from your entity class and overrides its virtual properties by inserting specific code useful for example for tracking changes and lazy loading.

The proxy instance has a dynamically generated name by the runtime that looks like this:

{System.Data.Entity.DynamicProxies User_00394CF1F92740F13E3EDBE858B6D599DFAF87AA5A089245977F61A32C75AA22}

(User is the original entity class name which the proxy class inherited from).

Starting from the proxy type, if you need to know the original type you have to use the static method GetObjectType of ObjectContext type, as shown in this example:

var userType = ObjectContext.GetObjectType(user.GetType());

Through the FullName property of the type returned by this method you can get the full name of the original type (User in this example)

Comments are closed.