8

I'm using Entity Framework. I've attached a POCO object representing an entity in the DB to my dbcontext using:

var entity = new MyEntity() { ID = 1, AnotherItemID = 10 };
context.Set<T>().Attach(entity);

So far so good. I can access the set and work with the entity I've added. It's added in the Unchanged state. However, it is only a POCO and not a Proxy. Therefore, when I try to access a navigation property, e.g. myEntity.AnotherItem, I just get a null back.

Does anyone know if there is a way to have EF resolve navigation properties for POCO classes attached in this way? Or of a way to cast the POCO to a proxy class?

Thanks

Update There are two ways to solve this (of course there may be others too!). One is the Explicit Loading option in the answer below. The other way, which allows lazy loading to work, is to use the DBSet Create method rather than the POCO new keyword when creating entities to be attached. More info about that here:

EF4.3 Code-First, MVC, Lazy Loading After Attaching in POST Action

1 Answer 1

8

You can use Explicity Loading:

 //When you want to load a reference navigation property
 context.Entry(entity).Reference(p => p.AnotherItem).Load(); 

 //When you want to load a collection navigation property
 context.Entry(post).Collection(p => p.Items).Load(); 
7
  • 2
    Hi @octavioccl thanks for the quick reply. I was trying to achieve a solution with lazy loading so I didn't have to think too much in advance about what to explicitly load. But perhaps I'm being a bit too lazy on this occasion!
    – Kate
    Commented Mar 1, 2016 at 13:32
  • Question, Are your navigation properties virtual, because that is a requirement for lazy loading. After the attach you should be able to lazy load your related entities.
    – ocuenca
    Commented Mar 1, 2016 at 14:06
  • Yes, they are virtual. They do lazy load if I actually retrieve the entity from DB. So should they lazy load automatically even when manually creating and attaching the entity? Perhaps I'm not attaching it correctly?
    – Kate
    Commented Mar 1, 2016 at 14:12
  • That's what I guess, but maybe I'm wrong, The truth is I haven't use lazy loading in these days, but maybe you can start creating your instance entity using Create method instead using new. Another way could be using Find method using the Ids of your entity.
    – ocuenca
    Commented Mar 1, 2016 at 14:21
  • I was just about to post about Create too! I found it mentioned on another question which I'll add as an update. It was indeed the key: using Create rather than new results in the entities being created as proxy classes and voila, lazy loading then works.
    – Kate
    Commented Mar 1, 2016 at 14:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.