unexpected GetType() result for entity entry

…衆ロ難τιáo~ 提交于 2019-11-27 19:40:13

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.

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(..)

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

Type t = entry.Entity.GetType().BaseType;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!