且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有EF Core Code First和IdentityUser的.Net Core API

更新时间:2023-02-09 10:35:26

This model worked for me(compiled, and no exceptions at runtime) if I used next code in the DbContext class:

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<BbUser>(b => b.ToTable("AspNetUsers"));
        base.OnModelCreating(builder);
    }

Without calling base.OnModelCreating(builder) I get the same error, because in this case context isn't applying the Identity related schema.

UPDATE: Everything works fine for me as you can see from the screenshot below:

I have one more idea why you can have such an error. Did your BbContext inherit from DbContext class or IdentityDbContext<IdentityUser>? Because I got the same error that was on your screenshot if I used usual DbContext class.

In order to Idenity tables work fine you should use IdentityDbContext<IdentityUser>. Below the whole code for my working DbContext class

 public class BbContext :IdentityDbContext<IdentityUser>
    {
        public BbContext(DbContextOptions options):base(options)
        {
            Database.EnsureCreated();
        }

        public DbSet<Artist> Artists { get; set; }
        public DbSet<Lyric> Lyrics { get; set; }
        public DbSet<Heart> Hearts { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<BbUser>(b => b.ToTable("AspNetUsers"));
            builder.Entity<Heart>().HasKey(h => new {h.UserId, h.LyricId});
            base.OnModelCreating(builder);
        }
    }