When does a linq Entity Framework query return dynamic proxy types, and when not?

I want to return one element from my context as follows

using (var context = new MyContext()) { var person = context.People.OrderByDescending(x => x.LastUpdatedDate).FirstOrDefault(); } 

My context looks like this:

 public DbSet<Person> People { get; set; } 

Why is the variable type my person above not Person , but the type of dynamic proxy, for example System.Data.Entity.DynamicProxies .Person_5E43C6C196972BF0754973E48C9C941092D86818CD94005E9A759B70BF6E48E6 ?

If I use Find , then I get the type as Person . I want to return the first record, as ordered by the last update date, and OrderByDescending / FirstOrDefault seemed the most logical.

I understand that I can turn off dynamic proxy generation, but I donโ€™t think it is necessary.

Suppose my question is, which linq methods force the object to return as the type you expect and which returns a dynamic proxy type?

+6
source share
1 answer

As I see in the source code of the Entity Framework , it is not associated with any linq method. When creating the result, it checks whether the value of ProxyCreationEnabled true, and then checks whether a proxy server can be created for the type, and then creates a proxy server for it. And here is the rule to check if proxy type can:

 private static bool CanProxyType(EntityType ospaceEntityType) { TypeAttributes access = ospaceEntityType.ClrType.Attributes & TypeAttributes.VisibilityMask; ConstructorInfo ctor = ospaceEntityType.ClrType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null, Type.EmptyTypes, null); bool accessableCtor = ctor != null && (((ctor.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public) || ((ctor.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Family) || ((ctor.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamORAssem)); return (!(ospaceEntityType.Abstract || ospaceEntityType.ClrType.IsSealed || typeof(IEntityWithRelationships).IsAssignableFrom(ospaceEntityType.ClrType) || !accessableCtor) && access == TypeAttributes.Public); } 

Also from this link msdn : Note that EF will not create proxies for types where there is nothing for the proxy. This means that you can also avoid proxies by using types that are sealed and / or have no virtual properties.

+3
source

All Articles