Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected GetType() result for entity entry

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?

like image 346
Anton Putov Avatar asked Apr 14 '13 21:04

Anton Putov


3 Answers

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.

like image 131
Gert Arnold Avatar answered Nov 19 '22 12:11

Gert Arnold


You can use

Type t = entry.Entity.GetType().BaseType;

or

ObjectContext.GetObjectType(entity.GetType())

But the second way is a better way from my point of view. If you call Type() request inside a Mapper method, for example DTO mapper (from entity object to DTO class or from in-memory objects to DTO class), ObjectContext.GetObjectType(..) will grant you always the expected result contrary to what will .GetType().BaseType

For example, if you use a TPT (Table per Type) strategy for EF Entity Model, call BaseType() on in-memory object will return the base class in hierarchy contrary to what will ObjectContext.GetObjectType(..)

enter image description here

like image 29
Enrico Tirotta Avatar answered Nov 19 '22 10:11

Enrico Tirotta


Another way is to access the BaseType property of the returned proxy type:

Type t = entry.Entity.GetType().BaseType;
like image 5
Good Night Nerd Pride Avatar answered Nov 19 '22 11:11

Good Night Nerd Pride