创建 ef6 dbcontext 构造函数 class

Creating a ef6 dbcontext constructor class

我是 Entity Framework 的新手,我正在尝试创建一个助手 class 来存储我的 dbcontext 配置设置,因为我下面的代码一直在重复我的项目,我想从一个地方调用它。

我也粘贴了我创建的内容,但我不确定在创建到我的数据库的 EF 连接时如何调用它。

using (dbEntities context = new dbEntities())
{
     // these same config settings are the same in each connection to the db I make
     context.Database.CommandTimeout = 9000000;
     context.Configuration.AutoDetectChangesEnabled = false;
     context.Configuration.ValidateOnSaveEnabled = false;

     //do some work here and upload to the db
}

// this is the helper class I created but I'm not sure how to call it when I use the above code
public class dbconfig : DbContext
{
    public dbconfig()
    {
        this.Database.CommandTimeout = 9000000;
        this.Configuration.AutoDetectChangesEnabled = false;
        this.Configuration.ValidateOnSaveEnabled = false;
    }
}

尝试关注

public class dbEntities : DbContext
{
  public dbEntities ()
    : base("someconnectionstring")
  {
    // Get the context related to this DbContext
    var context = (this as IObjectContextAdapter).ObjectContext;

    // Sets the common properties here
     context.Database.CommandTimeout = 9000000;
     context.Configuration.AutoDetectChangesEnabled = false;
     context.Configuration.ValidateOnSaveEnabled = false;
  }
}

但是,我必须指出,这将关闭整个应用程序的更改跟踪。但是,如果需要,您可以在使用 dbContext 的地方再次覆盖 in。

在 EF 中的 change tracking 上查看更多信息。

编辑

看看你能不能做到以下几点?

public class dbconfig : dbEntities
{
    public dbconfig()
    {
        this.Database.CommandTimeout = 9000000;
        this.Configuration.AutoDetectChangesEnabled = false;
        this.Configuration.ValidateOnSaveEnabled = false;
    }
}

然后

using (var context = new dbConfig())
{
      ///access dbsets
}