ASP.NET MVC 5数据库更新

时间:2018-04-30 21:30:14

标签: c# asp.net-mvc ef-migrations

我正在IdentityConfig.cs文件中初始化我的网站用户和角色数据,当我添加新模型而不是使用代码优先的add-migration和update-database命令将其映射到数据库时,我得到一个空的数据库:

public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
{
    protected override void Seed(ApplicationDbContext context)
    {
        InitializeIdentityForEF(context);
        base.Seed(context);
    }

    // Create User=aadmin2018@mail.com with Admin2018@mail.com in the Admin role
    public static void InitializeIdentityForEF(ApplicationDbContext db)
    {
        var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
        const string name = "admin2018@mail.com";
        const string password = "Admin2018@mail.com";
        const string roleName = "Admin";

        // Create role Admin if it does not exist
        var role = roleManager.FindByName(roleName);

        if (role == null)
        {
            role = new IdentityRole(roleName);
            var roleresult = roleManager.Create(role);
        }

        var user = userManager.FindByName(name);

        if (user == null)
        {
            user = new ApplicationUser
            {
                UserName = name,
                Email = name,
                FirstName = "Admin",
                LastName = "Admin",
                DateOfBirth = new DateTime(2015, 1, 1),
                Address = new Address
                {
                    AddressLine1 = "1 Admin Street",
                    Town = "Town",
                    County = "County",
                    Postcode = "PostCode"
                }
            };

            var result = userManager.Create(user, password);
            result = userManager.SetLockoutEnabled(user.Id, false);
        }

        // Add user admin to Role Admin if not already added
        var rolesForUser = userManager.GetRoles(user.Id);

        if (!rolesForUser.Contains(role.Name))
        {
            var result = userManager.AddToRole(user.Id, role.Name);
        }

        // Create users role
        const string userRoleName = "Users";
        role = roleManager.FindByName(userRoleName);

        if (role == null)
        {
            role = new IdentityRole(userRoleName);
            var roleresult = roleManager.Create(role);
        }
    }
}

我应该更改代码以便这些数据返回数据库?

0 个答案:

没有答案