Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4: Access current datacontext in partial entity class

I want to extend an EF entity in a partial class with methods and properties. I've done this quite often. But now I would need to combine data from this entity with data from other entities. I would therefore need to able to access the entities objectcontext (if attached) to make these queries. Is there a way to get the entities objectcontext from within it?

Thanx!

like image 648
SolarX Avatar asked Mar 06 '11 10:03

SolarX


2 Answers

There is no build in way to get current ObjectContext from entity. Entities based on EntityObject class and POCO proxies uses ObjecContext internally but they don't expose it.

Adding such depnedency into your entities is considered as bad design so you should perhaps explain what you are trying to do and we can find other (better) solution.

like image 164
Ladislav Mrnka Avatar answered Sep 25 '22 01:09

Ladislav Mrnka


Even though it is not recommended, and I myself don't use it (as Ladislav stated: bad design), I stumbled upon a solution:

http://blogs.msdn.com/b/alexj/archive/2009/06/08/tip-24-how-to-get-the-objectcontext-from-an-entity.aspx

Extension Method:

public static ObjectContext GetContext( 
   this IEntityWithRelationships entity 
) 
{ 
    if (entity == null)  
       throw new ArgumentNullException("entity"); 

    var relationshipManager = entity.RelationshipManager; 

    var relatedEnd = relationshipManager.GetAllRelatedEnds() 
                                        .FirstOrDefault(); 

    if (relatedEnd == null)  
       throw new Exception("No relationships found"); 

    var query = relatedEnd.CreateSourceQuery() as ObjectQuery; 

    if (query == null)  
       throw new Exception("The Entity is Detached"); 

    return query.Context; 
}

within the entity

var myContext = this.GetContext() as MyEntities;
like image 27
SolarX Avatar answered Sep 23 '22 01:09

SolarX