在数据库中未创建Asp.net核心身份表

时间:2018-07-05 16:19:51

标签: database asp.net-identity

当我在其他示例项目中看到时,为支持db中的Identity而创建的表的数量很大(例如AspNetRoles,AspNetUserClaims等),但是在我的情况下,我仅进行迁移和更新用户表已创建。是什么原因? 这是我在启动时,dbcontext中和我的类用户中的代码:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSession();
            services.AddMemoryCache();
            services.AddDbContext<ApplicationDbContext>( options =>
                             options.UseSqlServer(Configuration["Data:photoarchiver:ConnString"]));
            services.AddIdentity<User, IdentityRole > (
                opts => {
                    opts.Password.RequireDigit = false;
                    opts.Password.RequiredLength = 7;
                    opts.Password.RequireLowercase = true;
                    opts.Password.RequireUppercase = false;
                    opts.Password.RequireNonAlphanumeric = false;
                }).AddEntityFrameworkStores<ApplicationDbContext>();
        }

DbContext类:

public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions options) : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().ToTable("Users");
            modelBuilder.Entity<User>().HasMany(u => u.Photos).WithOne(i => i.User);

            modelBuilder.Entity<Photo>().ToTable("Photos");
            modelBuilder.Entity<Photo>().HasOne(i => i.User).WithMany(u => u.Photos);

            modelBuilder.Entity<Category>().ToTable("Categories");

        }

        public DbSet<Photo> Photos { get; set; }
        public DbSet<Category> Categories { get; set; }
    }

班级用户:

public class User : IdentityUser
    {
        public virtual List<Photo> Photos { get; set; }

        [Required]
        public string DisplayName { get; set; }
        public string Notes { get; set; }
        [Required]
        public DateTime CreatedDate { get; set; }

    }

1 个答案:

答案 0 :(得分:2)

要“免费”获得所有AspNetRoles, etc表,您需要将ApplicationDbContext更改为从IdentityDbContext<User>扩展而不仅仅是DbContext。在IdentityDbContext<T>名称空间中找到Microsoft.AspNetCore.Identity.EntityFrameworkCore。您可以从源代码https://github.com/aspnet/Identity/blob/master/src/EF/IdentityDbContext.cs中看到,IdentityDbContext将引入必需的DbSet属性。 正如您在问题注释中正确标识的那样,您需要调用base.OnModelCreating(builder)并重新制作迁移文件。