C#IdentityDbContext继续重新创建

时间:2018-06-05 04:15:37

标签: c# asp.net-mvc entity-framework authentication database-migration

当我更改任何模型时,我使用MigrateDatabaseToLatestVersion迁移我的数据库。

目前,我的网站,模型,数据库和服务都在不同的项目中共享EntityContext

当我启动应用程序时,它首先创建数据库,这很好,但是当我导航到另一个页面,或者与数据库进行交互时,我认为它试图再次重新创建数据库,或者某些东西因为应用程序只是挂起,但如果我取消注释:

static EntityContext() 
{
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<EntityContext, EntityConfiguration>());
}

它继续正常工作,所以我认为它与迁移部分有关。

这是我的配置:

我的背景: (DataAccessLayer项目)

public class EntityContext : IdentityDbContext<ApplicationUser>, IDbContext
{
    static EntityContext() 
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<EntityContext, EntityConfiguration>());
    }

    public EntityContext() : base("EntityContext", throwIfV1Schema: false)
    {
        Configuration.LazyLoadingEnabled = false;
        Configuration.AutoDetectChangesEnabled = false;
        Configuration.ProxyCreationEnabled = false;
        Configuration.ValidateOnSaveEnabled = false;
    }

    public static EntityContext Create()
    {
        return new EntityContext();
    }

我的配置: (DataAccessLayer项目)

internal sealed class EntityConfiguration : DbMigrationsConfiguration<EntityContext>
{
    public EntityConfiguration()
    {
        AutomaticMigrationsEnabled = false;

        #if DEBUG
        AutomaticMigrationDataLossAllowed = true;
        AutomaticMigrationsEnabled = true;
        #endif
    }

    protected override void Seed(EntityContext context)
    {
        [...]
    }

我的Startup.Auth.cs (网络项目)

    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(EntityContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Add Role Manager
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

最后我的IdentityConfig.cs (网络项目)

// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store)
    {

    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<EntityContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

        // Configure user lockout defaults
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
        {
            MessageFormat = "Your security code is {0}"
        });

        manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        {
            Subject = "Security Code",
            BodyFormat = "Your security code is {0}"
        });

        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();

        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider = 
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}

// Configure the application sign-in manager which is used in this application.
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
    public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) : base(userManager, authenticationManager)
    {
    }

    public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
    {
        return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
    }

    public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
    {
        return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
    }
}

// Add ApplicationRoleManager to allow the management of Roles
public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
    public ApplicationRoleManager(IRoleStore<ApplicationRole, string> store) : base(store)
    {

    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        var roleStore = new RoleStore<ApplicationRole>(context.Get<EntityContext>());
        return new ApplicationRoleManager(roleStore);
    }
}

0 个答案:

没有答案