接続されたプロパティを使用する別の解決策があります。
接続されたプロパティの使用は次のようになります(警告:テストされていないコード):
public partial class Database1Entities
{
private struct ObjectContextProperty { }
partial void OnContextCreated()
{
this.ObjectMaterialized += (_, e) =>
{
e.Entity.GetConnectedProperty<Database1Entities, ObjectContextProperty>().Set(this);
};
this.ObjectStateManager.ObjectStateManagerChanged += (_, e) =>
{
if (e.Action == CollectionChangeAction.Add)
{
e.Element.GetConnectedProperty<Database1Entities, ObjectContextProperty>().Set(this);
}
else if (e.Action == CollectionChangeAction.Remove)
{
e.Element.GetConnectedProperty<Database1Entities, ObjectContextProperty>().Set(null);
}
};
}
/// <summary>
/// Gets the object context for the entity. Returns <c>null</c> if the entity is detached.
/// </summary>
/// <param name="entity">The entity for which to return the object context.</param>
public static Database1Entities FromEntity(EntityObject entity)
{
return entity.GetConnectedProperty<Database1Entities, ObjectContextProperty>().GetOrConnect(null);
}
}
次に、を使用Database1Entities.FromEntity
して、エンティティオブジェクトからオブジェクトコンテキストを取得できます。必要に応じて、エンティティオブジェクトに実際のプロパティを定義することもできます。
public partial class Table1
{
/// <summary>
/// Gets the object context for this entity. Returns <c>null</c> if the entity is detached.
/// </summary>
public Database1Entities ObjectContext { get { return Database1Entities.FromEntity(this); } }
}
このソリューションではObjectContext
、エンティティオブジェクトのプロパティはオプションです。