I'm new to Entity Framework and I'm trying to create a helper class that I store my dbcontext
configuration settings in because the code I have below repeats all over my project and I want it called from one place.
I also pasted what I created but I'm not sure how to call this when I create an EF connection to my database.
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;
}
}
Just try following
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;
}
}
However, I must point out that this will switch off the change tracking for your entire application. Should the need arise however, you can again override in at the place where you use dbContext.
Have more look here on change tracking in EF.
EDIT
See if you can do following?
public class dbconfig : dbEntities
{
public dbconfig()
{
this.Database.CommandTimeout = 9000000;
this.Configuration.AutoDetectChangesEnabled = false;
this.Configuration.ValidateOnSaveEnabled = false;
}
}
And then
using (var context = new dbConfig())
{
///access dbsets
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.