创建了一个超级用户,但我的SQL AspNetUserRoles表列中没有填充任何内容

时间:2018-06-12 15:41:14

标签: c# asp.net-mvc entity-framework

我正在开发一个ASP.NET MVC项目,我正在跟踪视频。我创建了一个超级用户。当我进入我的SQL数据库并运行“SELECT * FROM AspNetUserRoles”时,UserId和RoleId下没有填充,但超级用户显示我运行“SELECT * FROM AspNetRoles”时。我很困惑为什么它不会填充UserId和RoleId。

我是ASP.NET MVC和C#的新手,所以如果我不清楚我想要完成什么,请原谅。我基本上试图设置一个AspNetUserRole。此外,当我运行update-database时,我得到“数据库中已经有一个名为'AspNetRoles'的对象。”我不知道这是否是我的问题的原因。我正在使用Microsoft.AspNetCore.Identity 2.0.2。先感谢您。这是我的代码:

DataSeeder.cs文件

using WebForums.Data.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace WebForums.Data
{
    public class DataSeeder
    {
        private ApplicationDbContext _context;

        public DataSeeder(ApplicationDbContext context)
        {
            _context = context;
        }

        public Task SeedSuperUser()
        {
            var roleStore = new RoleStore<IdentityRole>(_context);
            var userStore = new UserStore<ApplicationUser>(_context);

            var user = new ApplicationUser
            {
                UserName = "Prime305",
                NormalizedUserName = "PRIME305",
                Email = "pride@aol.com",
                NormalizedEmail = "PRIDE@AOL.COM",
                EmailConfirmed = true,
                LockoutEnabled = false,
                SecurityStamp = Guid.NewGuid().ToString()

            };

            var hasher = new PasswordHasher<ApplicationUser>();
            var hashedPassword = hasher.HashPassword(user, "admin123");
            user.PasswordHash = hashedPassword;

            var hasAdminRole = _context.Roles.Any(roles => roles.Name == "Admin");
            if (!hasAdminRole)
            {
                 roleStore.CreateAsync(new IdentityRole
                {
                    Name = "Admin",
                    NormalizedName = "admin"
                });
            }

            var hasSuperUser = _context.Users.Any(u => u.NormalizedUserName == user.UserName);

            if (!hasSuperUser)
            {
                 userStore.CreateAsync(user);
                 userStore.AddToRoleAsync(user, "Admin");
            }

             _context.SaveChangesAsync();

            return Task.CompletedTask;
        }
    }
}

Startup.cs文件

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebForums.Data;
using WebForums.Services;
using WebForums.Data.Models;
using WebForums.Service;

namespace WebForums

{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {    
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            // Add application services.
            services.AddTransient<IEmailSender, EmailSender>();
            services.AddScoped<IForum, ForumService>();
            services.AddScoped<IPost, PostService>();
            services.AddScoped<IUpload, UploadService>();
            services.AddScoped<IApplicationUser, ApplicationUserService>();

            /*services.AddAuthentication().AddGoogle(googleOptions =>
            {
                googleOptions.ClientId = Configuration["455316502795-pta3su9bbg6q59dhethmiqkmu69mlach.apps.googleusercontent.com"];
                googleOptions.ClientSecret = Configuration[""];
            });*/

            services.AddTransient<DataSeeder>();

            services.AddMvc();    
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, DataSeeder dataSeeder)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            dataSeeder.SeedSuperUser();

            app.UseStaticFiles();    
            app.UseAuthentication();    

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            /*app.UseGoogleAuthentication(options: new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "455316502795-pta3su9bbg6q59dhethmiqkmu69mlach.apps.googleusercontent.com",
                ClientSecret = "33t5J663I6WAzgjjFdA8pxo5"
            });*/

        }
    }
}

MSSMS中SQL数据库的屏幕截图: AspNetRole command AspNetUserRoles command 我想发生了什么是AspNetUserRole没有引用AspNetRoles,因为当我尝试运行这个时  Error ,我在“名字”下面得到那条红线。

0 个答案:

没有答案