C# 窗口窗体中的实体框架DbContext范围
我已经阅读了许多文章,但发现有关WindowsForms应用程序中DbContext范围的信息太少。到目前为止,我已经看到了以下实现: 1) 首次实施C# 窗口窗体中的实体框架DbContext范围,c#,winforms,entity-framework,desktop-application,dbcontext,C#,Winforms,Entity Framework,Desktop Application,Dbcontext,我已经阅读了许多文章,但发现有关WindowsForms应用程序中DbContext范围的信息太少。到目前为止,我已经看到了以下实现: 1) 首次实施 using(var db=new DbContext()) { // perform operations } public class A { private DbContext _db; public void DoSomething() { _db.Students.Find(1);
using(var db=new DbContext())
{
// perform operations
}
public class A
{
private DbContext _db;
public void DoSomething()
{
_db.Students.Find(1);
}
}
2) 第二次实施
using(var db=new DbContext())
{
// perform operations
}
public class A
{
private DbContext _db;
public void DoSomething()
{
_db.Students.Find(1);
}
}
3) 第三次执行
using(var db=new DbContext())
{
// perform operations
}
public class A
{
private DbContext _db;
public void DoSomething()
{
_db.Students.Find(1);
}
}
使用Singleton类初始化DbContext并在整个程序/应用程序中调用它
4) 第四次执行
using(var db=new DbContext())
{
// perform operations
}
public class A
{
private DbContext _db;
public void DoSomething()
{
_db.Students.Find(1);
}
}
将公共或设置类中的DbContext声明为静态属性,并在整个项目/应用程序中调用它
所以,我的问题是什么是应用程序中DbContext的最佳实现,为什么?其他不是最好的实现有哪些缺点?DbContext是一种工作单元模式,其设计目的是(a)实例化成本低,(b)寿命短
使用长寿命的DbContext可能会遇到很多问题。例如,检索到的实体会根据DbContext进行缓存,因此这可能会发生:有一些有效点。也请阅读重复的帖子。@RezaAghaei该问题不包含任何实现这意味着我应该使用第一个实现,但我见过许多专家使用单例实现