0

All,

I'm starting out with Entity Framework 4 (not CTP5 yet) and am looking at the complexities of migrating NHibernate to EF.

Some code we have tests if a collection or related entity is a proxy and, if so, performs some different code to normal. If the collection is not a proxy (i.e. it has already been loaded into the context) then we do something else directly against the collection.

I've migrated this code to use the IRelatedEnd interface for collections, but the act of casting my ICollection to IRelatedEnd causes EF to load the collection... the result is that the collection is never a proxy when I check for IsLoaded == true in the next line.

Do I need to do something extra considering this is a custom POCO or is this expected behaviour?

Likewise, is there anyway to test if a related entity is a proxy or not?

Many thanks

GrahamB
  • 1,368
  • 15
  • 35

1 Answers1

2

The suggested method over on MSDN to test for proxies is to use something like this:

public static bool IsProxy(object type)
{
    return type != null && ObjectContext.GetObjectType(type.GetType()) != type.GetType();
}

This method works in both EF 4 and EF 4.1 Codefirst.

As for the lazy loading, I've never use the IRelatedEnd - just left the navigation properties in the POCO's as ICollection and ensure that lazy loading is enabled. Beyond that, it just works.

context.ContextOptions.LazyLoadingEnabled = true;

There's also an option in the edmx for lazy loading.

Leniency
  • 4,984
  • 28
  • 36
  • Your answer is valid, but I want to point out this important point: if you just want to find the object's "real" type you can *always* use `ObjectContext.GetObjectType()` regardless of whether it is actually a dynamic proxy. I mention this because I found myself here for that reason but such checking is totally unnecessary. See: http://blogs.msdn.com/b/adonet/archive/2011/02/02/using-dbcontext-in-ef-feature-ctp5-part-8-working-with-proxies.aspx – Casey Feb 20 '14 at 15:47