在ASP.NET Identity 2.0.1中播种用户和角色时的奇怪之处

时间:2014-07-18 18:59:16

标签: c# asp.net-identity-2

我发现这件作品不能正常工作:

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");
}

创建角色但用户不是,然后第一个AddToRole失败。相反,如果用户首先添加(或更新)到数据库,那么它可以正常工作。

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");
}

任何人都可以解释这种看似奇怪的行为吗?为什么必须先创建用户?谢谢!!

2 个答案:

答案 0 :(得分:2)

必须先创建用户,然后才能将该用户添加到角色。将不存在的用户添加到角色是不切实际的。

答案 1 :(得分:0)

我无法重新创建您的方案,种子功能无法以任何顺序保存数据。但这就是我想出来的。

它之所以说&#34; UserId未找到&#34;并且行动不起作用是因为一切都在同一个交易中运行。

UserManager无法将用户与角色相关联,因为尚未创建用户。您需要完成当前事务(用户将被添加到数据库中)并启动一个新事务,然后您可以将角色添加到用户。

请参阅以下代码

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");
    }

要完成当前交易并开始新交易,您只需拨打&#34; SaveChanges&#34;从当前的背景来看。

查看以下代码的更改

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");

我使用此链接作为参考,但主要是通过测试。

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