繁体   English   中英

为什么在尝试创建用户时出现无效对象名称错误?

[英]Why am I getting an Invalid Object Name error when trying to create a user?

我有以下代码尝试通过新的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM