unexpected GetType() result for entity entry

前端 未结 3 1061
孤独总比滥情好
孤独总比滥情好 2020-12-05 06:41

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

foreach (ObjectStateEntry          


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 07:26

    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

提交回复
热议问题