Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF resolve navigation property after manual attach

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

like image 597
Kate Avatar asked Mar 01 '16 13:03

Kate


People also ask

What is reference navigation property?

Reference navigation property: A navigation property that holds a reference to a single related entity. Inverse navigation property: When discussing a particular navigation property, this term refers to the navigation property on the other end of the relationship.

What is navigation property in entity data model?

A navigation property is an optional property on an entity type that allows for navigation from one end of an association to the other end. Unlike other properties, navigation properties do not carry data.

How do I use lazy loading in entity Framework?

Lazy loading means delaying the loading of related data, until you specifically request for it. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook.


1 Answers

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(); 
like image 89
octavioccl Avatar answered Oct 13 '22 19:10

octavioccl