Get underlying entity object from entity framework proxy

前端 未结 6 1765
逝去的感伤
逝去的感伤 2020-12-04 16:41

I have an entity by getting it from DbEntityEntry.Entity. This returns the Entity Framework proxy for the entity.

How do I access the underlying object

6条回答
  •  执念已碎
    2020-12-04 17:09

    To get a JSON friendly object in EF Core I used this method:

    T UnProxy(T efObject) where T : new()
    {
        var type = efObject.GetType();
    
        if (type.Namespace == "Castle.Proxies")
        {
            var baseType = type.BaseType;
            var returnObject = new T();
            foreach (var property in baseType.GetProperties())
            {
                var propertyType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
                if (propertyType.Namespace == "System")
                {
                    var value = property.GetValue(efObject);
                    property.SetValue(returnObject, value);
                }
            }
            return returnObject;
        }
    
        return efObject;
    }
    

提交回复
热议问题