Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I recognise an EF POCO proxy without referencing EF?

I need to spot EF POCO proxies; MSDN gives some hints based around ObjectContext.GetObjectType(type.GetType())

However, I would really like to do this without the EF reference. For example, with NHibernate, I can check whether the object implements a marker interface, using the name (as a string) "NHibernate.Proxy.INHibernateProxy".

Is there anything similar in EF POCO proxies? For example can I rely on them being in the namespace System.Data.Entity.DynamicProxies., or is that brittle?

Taking a peek inside reflector, it simply checks the assembly against internally tracked assemblies, which is problematic for me.

like image 520
Marc Gravell Avatar asked Jul 15 '11 09:07

Marc Gravell


People also ask

What is Poco proxy in Entity Framework?

Thank you. When creating instances of POCO entity types, Entity Framework often creates instances of a dynamically generated derived type that acts as a proxy for the entity. This proxy overrides some virtual properties of the entity to insert hooks for performing actions automatically when the property is accessed.

How do I avoid creating proxies in EF?

Note that the EF will not create proxies for types where there is nothing for the proxy to do. This means that you can also avoid proxies by having types that are sealed and/or have no virtual properties. A proxy instance will not be created if you create an instance of an entity using the new operator.

How do I turn off proxy creation in Entity Framework?

this.ContextOptions. ProxyCreationEnabled= false; We can also disable creation of a proxy at the time of object creation of the context instead of disabling it at the constructor of the context. Entity Framework does not create proxie instances for the type where there is nothing to do with a proxy.

Why Entity Framework does not create proxie instances for sealed types?

Entity Framework does not create proxie instances for the type where there is nothing to do with a proxy. It means that we can avoid creating proxies for the type that are sealed or that have no virtual properties.


2 Answers

Checking under-the-hood, as an implementation detail it is indeed the case that in the current EF the type will always live in "System.Data.Entity.DynamicProxies". This probably isn't a robust test, but should change infrequently. I will attempt to clarify this with Microsoft, though.

like image 55
Marc Gravell Avatar answered Nov 10 '22 17:11

Marc Gravell


I know a POCO proxy type named as this pattern, UserDefinedName_123AF....

So how about this approach?

const string pattern = @"_[\dA-F]{64}\b";
Regex regex = new Regex(pattern);
bool result = regex.IsMatch(tragetObject.GetType().Name);
like image 44
Jin-Wook Chung Avatar answered Nov 10 '22 18:11

Jin-Wook Chung