创建一个ef6 dbcontext构造函数类。

问题描述 投票:-1回答:1

我是Entity Framework的新手,我想创建一个帮助类,用来存储我的 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;
    }
}
c# sql entity-framework entity-framework-6 dbcontext
1个回答
1
投票

试着按以下步骤操作

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的地方再次覆盖。

请看这里 变动追踪 在EF。

编辑

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

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
}
© www.soinside.com 2019 - 2024. All rights reserved.