我有下面的代码,试图通过新的asp.net Identity 2.0创建一个默认用户,如果在我的web应用程序首次运行时该用户实际上还不存在:
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