Entity Framework 4: Access current datacontext in partial entity class

后端 未结 2 1834
逝去的感伤
逝去的感伤 2021-01-12 03:44

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 fr

相关标签:
2条回答
  • 2021-01-12 04:36

    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 讨论(0)
  • 2021-01-12 04:43

    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.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题