Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 窗口窗体中的实体框架DbContext范围_C#_Winforms_Entity Framework_Desktop Application_Dbcontext - Fatal编程技术网

C# 窗口窗体中的实体框架DbContext范围

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);

我已经阅读了许多文章,但发现有关WindowsForms应用程序中DbContext范围的信息太少。到目前为止,我已经看到了以下实现:

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该问题不包含任何实现这意味着我应该使用第一个实现,但我见过许多专家使用单例实现