Entity Framework 4: Access current datacontext in partial entity class

后端 未结 2 1927
逝去的感伤
逝去的感伤 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;

提交回复
热议问题