0
我使用Code-First
以及Entity Framework 5
和Repository Pattern
。如何從實例化的POCO類中檢索上下文?
我需要從某些擴展方法內部獲取上下文以訪問其他無法通過屬性訪問的實體。
例子:
public static class MyClassExtensions
{
public static void DoSomething(this MyClass mClass)
{
// This is what I want to do
// GetContextSomeWay() is what I need
// GetRepository is method from my context
mClass.GetContextSomeWay().GetRepository<SomeRepository>().Where(...);
}
}
public class MyService
{
public void DoSomethingOnService(int id)
{
MyContext ctx = new MyContext();
MyClass cl = ctx.GetRepository<MyClass>().Single(c => c.Id == id);
cl.DoSomething();
}
}
我想到了兩個解決方案。
- 傳遞上下文作爲參數的擴展方法
- 使用
ObjectMaterialized
事件上下文設置爲每個實體
即使第一種方法是,沒有什麼麻煩的工作,我不能不要再認爲這不是一個好的做法。
第二,除了爲我的每個類添加一個新屬性的工作之外,我想知道這是否會成爲性能問題。這是過分的關注,還是這是有效的?
這個問題還有其他解決方案嗎?
謝謝,我會考慮這樣做。我的解決方案不會像我想的那樣理想,對吧? – eestein
就像你想要的那樣,你可以將你的服務層創建與它的使用分開。它非常容易使用,非常舒適。看看它,我相信你會喜歡它。 –
我做了,謝謝:) – eestein