c# - 为什么我在尝试创建用户时收到无效对象名称错误?

标签 c# asp.net-mvc asp.net-identity

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

关于c# - 为什么我在尝试创建用户时收到无效对象名称错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22951382/

相关文章:

asp.net - 我可以获取 OWIN cookie 并将其解密以在 BeginRequest 中从中获取声明吗?

asp.net-mvc - 如果不活动时间超过安全标记验证间隔,则 ASP.NET 身份注销失败

asp.net-mvc - Html.TextBoxFor 仅接受大于零的数字

c# - 尝试向用户添加角色时,Asp.NET 身份角色不起作用

C# mutex - 从 ASP.NET 和控制台应用程序调用时出错

c# - '~' 在 vi​​sual studio C# 中是什么意思/做什么

c# - 如何访问 x :Name-property in code?

C#,检查整数数组中是否有负数

c# - 用于呈现新闻和类别的 Razor ,多个模型

asp.net-mvc - 在 IIS7 上部署 MVC 应用程序的最佳实践