开发者

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 f开发者_如何学Pythonrom 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!


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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜