我有以下代码尝试通过新的 asp.net Identity 2.0 创建默认用户,如果实际上当我的网络应用程序首次运行时该用户尚不存在:

public class DotNetIdentity  
{ 
 
    // PROPERTIES 
 
    public UserManager<ApplicationUser, string> UserManager { get; private set; } 
    public RoleManager<IdentityRole> RoleManagement { get; private set; } 
 
    // CONSTRUCTORS 
    public DotNetIdentity() 
    { 
        // create the user manager 
        UserManager = new UserManager<ApplicationUser, string>(new UserStore<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, 
    CustomUserClaim>( 
            new myDbContext())); 
 
        #region Define user manager settings 
 
        // Configure validation logic for usernames 
        UserManager.UserValidator = new UserValidator<ApplicationUser, string> 
            ( 
            UserManager) 
                                    { 
                                        AllowOnlyAlphanumericUserNames = false, 
                                        RequireUniqueEmail = true 
                                    }; 
 
        // Configure validation logic for passwords 
        UserManager.PasswordValidator = new PasswordValidator() 
                                        { 
                                            RequiredLength = 6, 
                                            RequireNonLetterOrDigit = false, 
                                            RequireDigit = false, 
                                            RequireLowercase = false, 
                                            RequireUppercase = false 
                                        }; 
 
        // Configure user lockout defaults 
        UserManager.UserLockoutEnabledByDefault = true; 
        UserManager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); 
        UserManager.MaxFailedAccessAttemptsBeforeLockout = 15; 
 
        // Register two factor authentication providers. 
        UserManager.RegisterTwoFactorProvider 
            ("PhoneCode", new PhoneNumberTokenProvider<ApplicationUser, string>() 
                          { 
                              MessageFormat = "Your security code is: {0}" 
                          }); 
        UserManager.RegisterTwoFactorProvider 
            ("EmailCode", new EmailTokenProvider<ApplicationUser, string>() 
                          { 
                              Subject = "SecurityCode", 
                              BodyFormat = "Your security code is {0}" 
                          }); 
        UserManager.EmailService = new EmailService(); 
        UserManager.SmsService = new SmsService(); 
 
 
        #endregion 
 
        // create the role manager 
        RoleManagement = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>( 
            new myDbContext())); 
    } 
 
    public void CreateDefaultAdministrator() 
    { 
        // db connection 
        using (var db = new myDbContext()) 
        { 
            // create admin obj 
            var admin = new ApplicationUser() 
            { 
                Id = Guid.NewGuid().ToString(), 
                UserName = "Dev", 
                Email = "dev@blahblah.com", 
                IsActive = true 
            }; 
 
 
 
            // create user 
            var result = UserManager.Create(admin, "Blahblah*0"); 
 
            // check if role exist 
            if (!RoleManagement.RoleExists("Administrator")) 
            { 
                // Add Administrator Role 
                var createResult = RoleManagement.Create( 
                    new IdentityRole("Administrator")); 
            } 
 
            if (!RoleManagement.RoleExists("Developer")) 
            { 
                // Add Developer Role 
                var createResult = RoleManagement.Create( 
                    new IdentityRole("Developer")); 
            } 
 
            // add user to roles 
            var createdUser = UserManager.FindByName("Dev"); 
            if (createdUser != null) 
            { 
                UserManager.AddToRole(createdUser.Id, "Administrator"); 
                UserManager.AddToRole(createdUser.Id, "Developer"); 
            } 
        } 
    } 
} 

当上面的代码运行时,我得到错误无效的对象名称'dbo.ApplicationUsers'。代码正在与之通信的数据库是空的,所以我希望这段代码生成所需的表。我在 asp.net Identity 1.0 中有与此类似的代码,它运行良好。 我遗漏了什么或导致此错误的可能原因是什么。下面是 ApplicationUser 和相关类的代码:

public class CustomRole : IdentityRole<string, CustomUserRole> 
{ 
 
public CustomRole() { } 
 
    public CustomRole(string name) 
    { 
        Id = Guid.NewGuid().ToString(); 
        Name = name; 
    } 
} 
 
public class CustomUserRole : IdentityUserRole<string> 
{ 
    public string Id { get; set; } 
 
    public CustomUserRole() 
    { 
        Id = Guid.NewGuid().ToString(); 
    } 
} 
public class CustomUserClaim : IdentityUserClaim<string> { } 
 
public class CustomUserLogin : IdentityUserLogin<string> 
{ 
    public string Id { get; set; } 
 
    public CustomUserLogin() 
    { 
        Id = Guid.NewGuid().ToString(); 
    } 
} 
 
// define the application user 
public class ApplicationUser : IdentityUser<string, CustomUserLogin, CustomUserRole,  
    CustomUserClaim> 
{ 
    [Required] 
    public bool IsActive { get; set; } 
 
    public ApplicationUser() 
    { 
    } 
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> 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 partial class myDbContext : IdentityDbContext<ApplicationUser, CustomRole, string,  
    CustomUserLogin, CustomUserRole, CustomUserClaim> 
{ 
    static myDbContext() 
    { 
        Database.SetInitializer<myDbContext>(null); 
    } 
 
    public myDbContext() 
        : base("Name=myDbContext") 
    { 
    } 
 
    public DbSet<TestTable> TestTables { get; set; } 
 
    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
        modelBuilder.Configurations.Add(new TestTableMap()); 
    } 
} 
} 

请您参考如下方法:

我必须为我的项目启用迁移。这为我解决了这个问题。我用这篇文章来帮助我。 http://www.dotnet-tricks.com/Tutorial/entityframework/R54K181213-Understanding-Entity-Framework-Code-First-Migrations.html


评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

C# Excel 自动化仅在 Excel 可见时起作用