c# - Get underlying entity object from entity framework proxy -
i have entity getting dbentityentry.entity
. returns entity framework proxy entity.
how access underlying object it's original type instead of proxy?
alternatively need dynamically try cast proxy entity type. here's start..
var theentitytype = entityentry.entity; if (theentitytype.basetype != null && entitytype.namespace == "system.data.entity.dynamicproxies") theentitytype = entitytype.basetype; // need cast correct type var entityobject = (theentitytype)entityentry.entity; // won't work because `theentitytype` dynamic. // entites don't implement iconvertible
first should there no underlying object. proxy doesn't wrap entity object (decorator pattern), derives (inheritance). can't unwrap entity, can convert proxy base object. conversion (contrary casting) creates new object.
for conversion, can exploit fact of time, way proxies returned ef, compile time type of proxy base type. is, if proxy entered argument generic method, generic parameter inferred base type. feature allows create method want:
t unproxy<t>(dbcontext context, t proxyobject) t : class { var proxycreationenabled = context.configuration.proxycreationenabled; try { context.configuration.proxycreationenabled = false; t poco = context.entry(proxyobject).currentvalues.toobject() t; return poco; } { context.configuration.proxycreationenabled = proxycreationenabled; } }
explanation
the proxy object enters method. type inferred base poco type. can temporarily turn off proxycreationenabled
on context , copy proxy object object of base poco type. copy action gratefully uses few ef features.
Comments
Post a Comment