实体框架数据库初始化:初始化新的Azure SqlDatabase时超时
我有一个ASP.NET MVC应用程序。当通过CustomerController创造了一个新的客户我运行一个新的后台任务(使用HostingEnvironment.QueueBackgroundWorkItem)创建一个新的Azure的SqlDatabase该客户。实体框架数据库初始化:初始化新的Azure SqlDatabase时超时
我使用实体框架代码首先创建/初始化新的数据库。下面的代码:
// My ConnectionString
var con = "...";
// Initialization strategy: create db and execute all Migrations
// MyConfiguration is just a DbMigrationsConfiguration with AutomaticMigrationsEnabled = true
Database.SetInitializer(strategy: new MigrateDatabaseToLatestVersion<CustomerDataContext, MyConfiguration>(useSuppliedContext: true));
using (var context = new CustomerDataContext(con))
{
// Neither 'Connection Timeout=300' in ConnectionString nor this line helps -> TimeoutException will rise after 30-40s
context.Database.CommandTimeout = 300;
// create the db - this lines throws the exception after ~40s
context.Database.Initialize(true);
}
我的问题是,我总是得到TimeoutException异常后约40秒。我认为这是因为Azure无法在短时间内初始化新的数据库。不要误会我的意思:Azure会很好地创建数据库,但我想等待那个点/摆脱TimeoutException。
EDIT1: 我使用连接超时= 300在我的ConnectionString,但我的应用程序并不真正关心的是;在大约40年后,我总是碰到一个SqlError。
EDIT2: 这提出了一个例外是SQLEXCEPTION。 消息:超时已过期。操作完成之前超时的时间或服务器没有响应。 来源:.net SqlClient数据提供
EDIT3: 我现在可以confim,这已经无关ASP.NET/IIS。即使在一个简单的UnitTest方法中,上面的代码也会失败。
在使用Code First Migrations时,似乎还有另一个CommandTimeout设置涉及数据库初始化过程。我想在这里分享我的解决方案,以防万一有人遇到这个问题。
感谢Rowan Miller他的提示指向我的解决方案。
这里是我的代码:
// Initialisation strategy
Database.SetInitializer(strategy: new CreateDatabaseIfNotExists<MyDataContext>());
// Use DbContext
using (var context = new MyDataContext(myConnectionString))
{
// Setting the CommandTimeout here does not prevent the database
// initialization process from raising a TimeoutException when using
// Code First Migrations so I think it's not needed here.
//context.Database.CommandTimeout = 300;
// this will create the database if it does not exist
context.Database.Initialize(force: false);
}
而且我Configuration.cs类:
public sealed class Configuration : DbMigrationsConfiguration<MyDataContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
AutomaticMigrationDataLossAllowed = false;
// Very important! Gives me enough time to wait for Azure
// to initialize (Create -> Migrate -> Seed) the database.
// Usually Azure needs 1-2 minutes so the default value of
// 30 seconds is not big enough!
CommandTimeout = 300;
}
}
命令超时和连接超时是两个不同的设置。在这种情况下,你只能增加commandtimeout。您可以增加web.config中的连接超时值:Connection Timeout=120
。您想要增加连接超时的唯一时间是在创建数据库时。
感谢您的提示,但不幸的是,这并没有改变任何东西。我的ConnectionString已经在使用Connection Timeout:Server = XXX.database.windows.net; Database = DB_Customer_34; User Id = XXX; Password = XXX; Connection Timeout = 240; MultipleActiveResultSets = True; Encrypt = True; App = EntityFramework – mmmato
你能分享你所看到的实际例外,完整的错误消息?谢谢! –
我已添加例外。谢谢。 – mmmato
您的迁移配置类中还有一个CommandTimeout属性,您可以尝试设置该属性。 https://msdn.microsoft.com/en-us/library/system.data.entity.migrations.dbmigrationsconfiguration.commandtimeout(v=vs.113).aspx –