Entity Framework 4: Access current datacontext in partial entity class

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-09 03:11:11

问题


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!


回答1:


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.




回答2:


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;


来源:https://stackoverflow.com/questions/5210080/entity-framework-4-access-current-datacontext-in-partial-entity-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!