MVC IdentityServer Db Empty Usertable / Error seeding

时间:2017-11-25 11:23:55

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

我是MVC的新手,我的webserve存在这个问题,我似乎无法修复。 在我的Dbinit中,我将用户添加到用户表中,并将一些成分添加到我制作的Ingredients表中。 成分被添加到表中没有任何问题。 但是,用户根本没有添加(dbo.AspNetUsers为空)。

当我运行程序时,我在Initialize任务中遇到异常(在DbInitializer中)> InvalidOperationException和错误消息“Error Seeding Database”。这是我在Program.cs中实现的异常:

public static void Main(string[] args)
    {
      var host = BuildWebHost(args);

      using (var scope = host.Services.CreateScope())
      {
        var services = scope.ServiceProvider;
        try
        {
          var context = services.GetRequiredService<AppDbContext>();
          var dbInit = services.GetRequiredService<IDBInitializer>();

          dbInit.Initialize(context).GetAwaiter().GetResult();
        }
        catch (Exception ex)
        {
          var log = services.GetRequiredService<ILogger<Program>>();
          log.LogError(ex, "Error seeding Database.");
        }
       }

      host.Run();
    }

我不确定此异常是否与我的问题有关,但我一直在尝试修复它。 我的DbIinitializer继承自一个只包含任务定义的接口。 我在Startup.cs中调用IDBInitializer和DBInitializer,其中DBInitializer失败。 这是我的DBInitializer代码:

namespace mvcServer.Data
{
    public class DBInitializer : IDBInitializer
    {
      private readonly UserManager<User> userManager;
      private readonly RoleManager<IdentityRole> roleManager;

      public DBInitializer(UserManager<User> userManager, RoleManager<IdentityRole> roleManager)
      {
        this.userManager = userManager;
        this.roleManager = roleManager;
      }

    public async Task Initialize(AppDbContext context)
      {
        context.Database.EnsureCreated();

        // Look for any users
        if (context.Users.Any())
        {
          return; // Db has been seeded.
        }

      // Create roles
      await roleManager.CreateAsync(new IdentityRole("user"));

      // Populate Ingredients table
      context.Ingredients.AddRange(
        new Ingredient { Name = "Potato", Category = "Vegetable", Allergen = "Gluten", IsSafe = true },
        new Ingredient { Name = "Strawberry", Category = "Fruit", Allergen = "Sugar", IsSafe = false });

      await context.SaveChangesAsync();

        var user = new User
        {
          Name = "Andrea",
          Lastname = "X",
          AccessFailedCount = 0,
          Email = "andrea@gmail.com",
          NormalizedEmail = "ANDREA@GMAIL.COM",
          EmailConfirmed = false,
          LockoutEnabled = true,
          TwoFactorEnabled = false,
          UserName = "andrea",
          NormalizedUserName = "ANDREA"
        };

        var userResult = await userManager.CreateAsync(user, "Password123");
        var roleresult = await userManager.AddToRoleAsync(user, "user");

        if (userResult.Succeeded)
        {
          var currUser = await userManager.FindByNameAsync(user.UserName);

          // Assigns claims for security
          var claims = new List<Claim> {
                      new Claim(type: JwtClaimTypes.GivenName, value: user.Name),
                      new Claim(type: JwtClaimTypes.FamilyName, value: user.Lastname),
                  };
          await userManager.AddClaimsAsync(currUser, claims);

        }
        else
        {
          Debug.WriteLine(userResult.ToString());
        }
    }
  }
}

是不是因为我使用context.Ingredients.AddRange而不是Async方法添加成分?虽然我已经尝试过但它什么也没做。 我也不确定是否需要丢弃我的迁移并在更改此类内容时完全重启。

这是Exception

System.InvalidOperationException
Message: Error seeding Database. Failed method:
Microsoft.AspNetCore.Identity.UserManager'1+<ValidateUserInternal>d_169.MoveNext

如果我需要提供更多代码或其他任何内容,请通知我。

编辑: AppDbContext:

namespace mvcServer.Data
{
    public class AppDbContext : IdentityDbContext<User>
    {
      public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
      {
      }

    public DbSet<Ingredient> Ingredients { get; set; }
  }
}

0 个答案:

没有答案