C# 创建ef6 dbcontext构造函数类
我是Entity Framework的新手,我正在尝试创建一个helper类来存储我的C# 创建ef6 dbcontext构造函数类,c#,sql,entity-framework,entity-framework-6,dbcontext,C#,Sql,Entity Framework,Entity Framework 6,Dbcontext,我是Entity Framework的新手,我正在尝试创建一个helper类来存储我的dbcontext配置设置,因为下面的代码在我的项目中重复,我希望从一个地方调用它 我还粘贴了我创建的内容,但我不确定在创建到数据库的EF连接时如何调用它 using (dbEntities context = new dbEntities()) { // these same config settings are the same in each connection to the db I ma
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的位置再次重写
有更多关于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
}
您必须将该代码放在
dbEntities
构造函数中,而不是放在不相关类的构造函数中。您在哪种应用程序中使用该代码?WPF/web/console?你的意思是说你也有一个类dbEntities继承自DbContext吗?@kuldeep我正在一个控制台应用程序中使用此代码,而从DbContext继承的类是我试图弄清楚如何在我的应用程序中实现此功能dbEntities类是从我的应用程序自动生成的代码。我在自动生成的类中使用了您的代码,这似乎很有效,但我试图提供一个单独的类,在自动生成的类被删除或发生其他情况时执行相同的操作。我不知道如何创建一个单独的dbcontext类来代替标题在这种情况下(自动生成的代码被删除,上下文也将被删除)应用程序在运行时如何与DB通信?我的意思是,设置配置的代码是否重要?是的,这正是我想要的。我简直不敢相信我竟然没有考虑继承dbentities类