我想知道什麼是在類之間傳遞上下文的最佳方式。我應該使用參考參數還是簡單地將上下文作爲參數傳遞?最好是構造函數,但在靜態方法的情況下,最好的方法是什麼?即性能,安全性,設計等等。在將上下文作爲參數傳遞的過程中是否存在性能問題?如果不同的線程在使用引用的同時在上下文中工作,可能會發生衝突嗎?將實體上下文傳遞給其他方法和對象
Main.cs
static void Main(string[] args)
{
var context = new MyEntities();
var myClass = new MyClass(context);
myClass.AddPerson();
// or
Person.AddPerson(ref context);
}
MyClass.cs
public class MyClass
{
public void MyClass(MyEntities context) { }
public void AddPerson()
{
context.People.AddObject(new Person());
}
}
MySecondClass.cs
public partial class Person
{
public static AddPerson(ref MyEntities context)
{
// Do something
}
}
當您將實體框架上下文作爲普通參數傳遞時,沒有問題或性能問題。只要確保它終於被處置。 – Andrei 2013-04-22 18:50:38
上下文類不是線程安全的,因此,如果您在多個線程中使用上下文,則無論使用或不使用'ref'修飾符傳遞它,都必須期望出現問題。您必須通過手動線程同步來確保線程安全(使用'lock'等)。如果你真的不需要它,你最好避免在不同的線程中使用上下文。 – Slauma 2013-04-22 18:59:28