我有一个网站,它从发送给用户的电子邮件中获取输入(一封电子邮件被发送给每个人,他们单击一个调用控制器操作的链接)。我想使用网络作业发送电子邮件,但我需要循环访问数据库中的所有用户以获取电子邮件地址。
我建立了网站,一切都很好。我在这里有从 IdentityDbContext 继承的 DbContext:
public class MooodDbContext : IdentityDbContext<ApplicationUser>
{
public MooodDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Response> Response { get; set; }
public DbSet<Cow> Cow { get; set; }
public DbSet<Herd> Herd { get; set; }
}
ConfigureServices 在我启动 webapp 时运行
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<MooodDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MooodConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<MooodDbContext>()
.AddDefaultTokenProviders();
services.AddMvc(options => options.Filters.Add(typeof(UnauthorizedExceptionFilterAttribute)));
services.AddScoped<IDbInitializer, DbInitializer>();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
但显然不是当我运行网络作业时。因此,当我尝试访问上下文中的任何内容时,我得到了这个异常(在设置 context = new context() 之后):
System.InvalidOperationException occurred
HResult=0x80131509
Message=No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
Source=Microsoft.EntityFrameworkCore
在我看来,这是因为我没有在 DbContext 上进行任何配置,但我不确定。有没有更好的方法来实现这一点?还是我错过了一些小东西?
编辑:这是我的网络作业的 program.cs(减去电子邮件功能,这是杂乱的):
private static MooodDbContext _context;
// Please set the following connection strings in app.config for this WebJob to run:
// AzureWebJobsDashboard and AzureWebJobsStorage
private static void Main()
{
_context = new MooodDbContext(new DbContextOptions<MooodDbContext>());
var host = new JobHost();
EmailAllHerds();
host.RunAndBlock();
EmailAllHerds();
}