仅在创建数据库时如何初始化身份?

问题描述

MVC的新手。

我似乎陷入了Catch-21的困境(不像Catch-22那样严重)。

为了减少不必要的数据库流量,我想仅在首次创建数据库时(例如,在CreateDatabaseIfNotExists(Of ApplicationDbContext)期间,调用我的方法来填充初始Identity数据(创建admin用户,admin角色等)。 )。

麻烦源于我的启动配置必须先设置DbContext,然后再设置ApplicationUserManagerApplicationSignInManager的事实:

Builder.CreatePerOwinContext(AddressOf ApplicationDbContext.Create)
Builder.CreatePerOwinContext(Of ApplicationUserManager)(AddressOf ApplicationUserManager.Create)
Builder.CreatePerOwinContext(Of ApplicationSignInManager)(AddressOf ApplicationSignInManager.Create)

ApplicationUserManager.Create()方法调用ApplicationDbContext,因此调用必须按该顺序进行。

以下是我的身份初始化代码的相关内容

Public Shared Sub InitializeIdentity()
  Dim oUserManager As ApplicationUserManager
  Dim oRoleManager As ApplicationRoleManager

  oUserManager = HttpContext.Current.GetowinContext.GetUserManager(Of ApplicationUserManager)
  oRoleManager = HttpContext.Current.GetowinContext.Get(Of ApplicationRoleManager)

  ...

End Sub

看到问题了吗? ApplicationUserManager依赖于ApplicationDbContext,而ApplicationDbContext依赖于ApplicationUserManager(仅当我尝试从覆盖的InitializeIdentity()方法运行Migrations.Configuration.Seed()时才使用后者)。

当然,我可以将InitializeIdentity()调用放在启动文件的其他位置,但是当第一次创建数据库时只需要运行一次时,它将在每个页面加载时运行。这是对数据库的大量完全不必要的点击。

是否有办法逃避此逻辑循环?我如何告诉框架在设置ApplicationUserManager之后(首先创建上下文时)必须先设置上下文,然后在 var sendGridMessage = new SendGridMessagae(); sendGridMessage.AddTo(receiverEmail,receiverName); sendGridMessage.From = new EmailAddress(senderEmail,senderName); sendGridMessage.Subject = subjectName; sendGridMessage.PlainTextContent = plainText; sendGridMessage.HtmlContent = htmlText; sendGridMessage.AddAttachment(fileName,"test"); 之后运行身份初始化?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)