jer*_*h91 10 c# asp.net connection-string hangfire
我在我的ASP .Net MVC Web App中使用了Hangfire,它已成功安装.我想使用相同的LocalDb来存储Hangfire的排队作业,以便像我以前用于存储数据一样出列和处理.但是我遇到下面的错误,当我提供了定义它的connectionString或名称Web.config中Startp.cs.我在添加时没有遇到任何麻烦,在hangfire之前删除了同一localDb中的更新数据.
Cannot attach the file 'c:\users\jerry_dev\documents\visual studio 2013\Projects\Hangfire.Highlighter\Hangfire.Highlighter\App_Data\aspnet-Hangfire.Highlighter-20150113085546.mdf' as database 'aspnet-Hangfire.Highlighter-20150113085546'.
Startup.cs:
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
app.UseHangfire(config =>
{
string hangfireConnectionString = @"Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Hangfire.Highlighter-20150113085546.mdf;Initial Catalog=aspnet-Hangfire.Highlighter-20150113085546;Integrated Security=True";
config.UseSqlServerStorage(hangfireConnectionString);
config.UseServer();
});
}
Run Code Online (Sandbox Code Playgroud)
我的项目解决方案名为"Hangfire.Highlighter"
Web.config:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Hangfire.Highlighter-20150113085546.mdf;Initial Catalog=aspnet-Hangfire.Highlighter-20150113085546;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Run Code Online (Sandbox Code Playgroud)
Jac*_*ack 20
我知道这已经过时了 - 但是已经有9个月了,我也把头发拉了过来 - 并决定在这里写一篇文章.
我的解决方案是创建一个快速而脏的DbContext,将其指向正确的连接字符串,并在构造函数中调用Database.CreateIfNotExists:
public class HangfireContext : DbContext
{
public HangfireContext() : base("name=HangfireContext")
{
Database.SetInitializer<HangfireContext>(null);
Database.CreateIfNotExists();
}
}
Run Code Online (Sandbox Code Playgroud)
在HangfireBootstrapper.Start()方法中,我执行以下操作:
public void Start()
{
lock (_lockObject)
{
if (_started) return;
_started = true;
HostingEnvironment.RegisterObject(this);
//This will create the DB if it doesn't exist
var db = new HangfireContext();
GlobalConfiguration.Configuration.UseSqlServerStorage("HangfireContext");
// See the next section on why we set the ServerName
var options = new BackgroundJobServerOptions()
{
ServerName = ConfigurationManager.AppSettings["HangfireServerName"]
};
_backgroundJobServer = new BackgroundJobServer(options);
var jobStarter = DependencyResolver.Current.GetService<JobBootstrapper>();
//See the Recurring Jobs + SimpleInjector section
jobStarter.Bootstrap();
}
}
Run Code Online (Sandbox Code Playgroud)
不确定为什么Hangfire在LocalDb上遇到这么困难 - 也许它只能处理成熟的SQL实例?无论哪种方式,这适用于我,新团队成员,以及站起来的新dev/staging/prod实例.
DB已经创建了吗?您可以尝试使用不同的连接字符串格式吗?类似这样的“Server=.;Database=HangFire.Highlighter;Trusted_Connection=True;”