简体   繁体   English

在ASP.NET Identity 2.0.1中播种用户和角色时发生奇怪的事情

[英]Strange thing when seeding users and roles in ASP.NET Identity 2.0.1

I found this piece does not work properly: 我发现此作品无法正常工作:

protected override void Seed(PintxoLista.Models.ApplicationDbContext context)
{
    var store = new RoleStore<IdentityRole>(context);
    var manager = new RoleManager<IdentityRole>(store);
    if (!context.Roles.Any(r => r.Name == "WeddingGuest"))
    {
        var role = new IdentityRole { Name = "WeedingGuest" };
        manager.Create(role);
    }

    if (!context.Roles.Any(r => r.Name == "BrideGroom"))
    {
        var role = new IdentityRole { Name = "BrideGroom" };
        manager.Create(role);
    }

    if (System.Diagnostics.Debugger.IsAttached == false)
    {
        System.Diagnostics.Debugger.Launch();
    }

    context.Users.AddOrUpdate(i => i.Id,
        new ApplicationUser
    {
        Id = "1",
        UserName = "han",
        Email = "hansolo1@rebels.com",
        PasswordHash = new PasswordHasher().HashPassword("1"),
        SecurityStamp = string.Empty
    },
    new ApplicationUser
    {
        Id = "2",
        UserName = "lando",
        Email = "lando@rebels.com",
        PasswordHash = new PasswordHasher().HashPassword("1"),
        SecurityStamp = string.Empty
    });

    var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    userManager.AddToRole("1", "WeedingGuest");
    userManager.AddToRole("2", "BrideGroom");
}

The roles are created but the users are not and then the first AddToRole fails. 将创建角色,但不会创建用户,然后第一个AddToRole失败。 Instead, if the users are add (or updated) to the database first then it works fine. 相反,如果首先将用户添加(或更新)到数据库,那么它将正常工作。

protected override void Seed(PintxoLista.Models.ApplicationDbContext context)
{
    context.Users.AddOrUpdate(i => i.Id,
        new ApplicationUser
    {
        Id = "1",
        UserName = "han",
        Email = "hansolo1@rebels.com",
        PasswordHash = new PasswordHasher().HashPassword("1"),
        SecurityStamp = string.Empty
    }, new ApplicationUser
    {
        Id = "2",
        UserName = "lando",
        Email = "lando@rebels.com",
        PasswordHash = new PasswordHasher().HashPassword("1"),
        SecurityStamp = string.Empty
    });

    var store = new RoleStore<IdentityRole>(context);
    var manager = new RoleManager<IdentityRole>(store);
    if (!context.Roles.Any(r => r.Name == "WeddingGuest"))
    {
        var role = new IdentityRole { Name = "WeedingGuest" };
        manager.Create(role);
    }

    if (!context.Roles.Any(r => r.Name == "BrideGroom"))
    {
        var role = new IdentityRole { Name = "BrideGroom" };
        manager.Create(role);
    }

    var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    userManager.AddToRole("1", "WeedingGuest");
    userManager.AddToRole("2", "BrideGroom");
}

Can anyone explain this apparently strange behaviour? 谁能解释这种看似奇怪的行为? Why the users must be created first? 为什么必须首先创建用户? Thank you!! 谢谢!!

A user must be created before that user can be added to a role. 必须先创建一个用户,然后才能将该用户添加到角色中。 It would be impractical to add a non-existent user to a role. 将不存在的用户添加到角色中是不切实际的。

I couldn't recreated your scenario, the seed function didn't save the data in any order. 我无法重新创建您的方案,种子函数没有按任何顺序保存数据。 But this is what I figured out. 但这就是我想出的。

The reason why it's saying "UserId not found" and the action isn't working is because everything is running in the same transaction. 之所以说“未找到UserId”并且该操作不起作用,是因为所有内容都在同一事务中运行。

The UserManager cannot link an user with a role because the user hasn't been created yet. 因为尚未创建用户,所以UserManager无法将用户与角色链接。 You need to finish the current transaction (the user will be added to the DB) and start a new one, then you can add the roles to the user. 您需要完成当前事务(将用户添加到数据库中)并开始新事务,然后可以将角色添加到用户。

See the code below 见下面的代码

protected override void Seed(MyProject.Dal.Context.MyProjectDbContext context)
    {
        context.Users.AddOrUpdate(u => u.Id, new Core.Entities.ApplicationUser{
             Id = "1",
             UserName = "foo@a.com",
             Email = "foo@a.com",
             PasswordHash = new PasswordHasher().HashPassword("@edulopezTest"),
             SecurityStamp = string.Empty,
             Names = "Test",
             LastNames = "Admin",
             BirthDate = DateTime.Now,
         });

       var  RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
       if (!context.Roles.Any(r => r.Name == "SuperAdmin"))
       {
           var role = new IdentityRole { Name = "SuperAdmin" };
           RoleManager.Create(role);
       }

       //**********************************************************
       //THIS IS ANOTHER WAY TO ADD THE ROLES. IT GIVE SAME RESULTS
       //**********************************************************
       //context.Roles.AddOrUpdate(r => r.Name,
       //    new IdentityRole { Name = "SuperAdmin" }    // 1
       //   , new IdentityRole { Name = "Admin" }         // 2
       //   );  

    var userManager = new UserManager<Core.Entities.ApplicationUser>(new UserStore<Core.Entities.ApplicationUser>(context));          
    userManager.AddToRole("1", "SuperAdmin");
    }

To finish the current transaction and start a new one you just need to call "SaveChanges" from the current context. 要完成当前事务并开始新事务,您只需要从当前上下文中调用“ SaveChanges”。

see changes on the code below 查看以下代码的更改

context.SaveChanges(); // <-- Finish and start a new one
var userManager = new UserManager<Core.Entities.ApplicationUser>(new UserStore<Core.Entities.ApplicationUser>(context));          
userManager.AddToRole("1", "SuperAdmin");

I used this links as reference but mostly was by doing tests. 我使用此链接作为参考,但主要是通过测试。

http://blog.oneunicorn.com/2013/05/28/database-initializer-and-migrations-seed-methods/ https://msdn.microsoft.com/en-us/data/jj554735 http://blog.oneunicorn.com/2013/05/28/database-initializer-and-migrations-seed-methods/ https://msdn.microsoft.com/en-us/data/jj554735

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

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