【问题标题】:Access dbcontext at startup在启动时访问 dbcontext
【发布时间】:2019-12-29 00:07:20
【问题描述】:

.NET MVC5 应用程序使用标识 2。

我需要在应用程序启动时调用我的服务的方法,但该方法需要访问数据库。我在哪里以及如何做到这一点?

【问题讨论】:

    标签: c# asp.net-mvc entity-framework asp.net-identity-2


    【解决方案1】:

    IdentityModel.cs 是需要修改的地方

    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }
    
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }
    
        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
    

    您可以创建多个环境变量,而不是默认连接。希望这回答了你的问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 2011-11-10
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 2018-09-15
      • 1970-01-01
      相关资源
      最近更新 更多