unexpected GetType() result for entity entry

前端 未结 3 1065
孤独总比滥情好
孤独总比滥情好 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:27

    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.

提交回复
热议问题