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