還有另一種解決方案,使用connected properties。
使用連接的屬性應該是這樣的(警告:未經測試的代碼):
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
屬性:您還可以定義在實體對象的實際屬性,以及如果你想要的。
感謝您的確切答覆,拉迪斯拉夫。我必須不同意你的說法,「這是你應該儘可能避免的事情」。顯然,這是必要的,否則關於如何做的問題和帖子將永遠不會寫出來。有一種方法可以獲得對大多數實體實例的ObjectContext的引用,但效率不高。有許多有效的場景需要從對象本身檢索對象的上下文,特別是需要與實體框架模型當前不支持的數據相關操作的擴展方法。 – 2011-04-19 01:49:46