unexpected GetType() result for entity entry

Anton Putov picture Anton Putov · Apr 14, 2013 · Viewed 12.3k times · Source

While I iterating through ObjectStateEntries I expected [t] variable name will be MY_ENTITY

foreach (ObjectStateEntry entry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted))
{
    Type t = entry.Entity.GetType();
    ...
}

but real I have

System.Data.Entity.DynamicProxies.MY_ENTITY_vgfg7s7wyd7c7vgvgv.....

How can I determine can I cast current entry to MY_ENTITY type?

Answer

Gert Arnold picture Gert Arnold · Apr 15, 2013

You can get the original entity type of a proxy type by

ObjectContext.GetObjectType(entity.GetType())

This is a static method of ObjectContext, so you can readily use in in a DbContext environment.

If for some reason you need the actual entity as its original type you can use the pattern

var entity = entry.Entity as MyEntity;
if (entity != null)
{
    ...
}

This is slightly more efficient than

if (entry.Entity is MyEntity)
{
    var entity = (MyEntity)entry.Entity;
    ...
}

because the latter snippet casts the object twice.