Ef Core 3.1 和 Identity 框架结合 DB Context

Ef Core 3.1 and Identity framework combining DB Context

我正在尝试将我的应用程序上下文与我的数据库上下文合并我已经尝试了各种解决方案,但是 none 其中的解决方案适用于 ef core 3.1。

public class AppManagerDBContext : IdentityDbContext
{
    public AppManagerDBContext(DbContextOptions options) : base(options) { }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("name=DefaultConnection");
        }
    }

    public DbSet<BmiInformation> BmiInformation { get; set; }
    public DbSet<WorkOuts> WorkOuts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<BmiInformation>().ToTable("BmInformation");            
    }
}

这是我得到的完整错误我认为我所要做的就是继承自 IdentityDbContext 在 .NET Core 3.1 和 EF Core 中我还需要做些什么吗?

Add-Migration MyFirstMigration -Context AppManagerDBContext
Build started...
Build succeeded.

错误

The AppManagerDBContext constructor must be a DbContextOptions. When registering multiple DbContext types make sure that the constructor for each context type has a DbContextOptions parameter rather than a non-generic DbContextOptions parameter.

编辑 1 好的,我通过以下方法解决了这个问题,但是我现在遇到了一个新错误。

我的用户信息class

public class UserInfo : IdentityUser
{
    // These two new fields are added here
    [PersonalData]
    public string Name { get; set; }
    [PersonalData]
    public DateTime DOB { get; set; }
}

错误 2

The entity type 'IdentityUserLogin' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'.

您必须将 DbContextOptions 对象注入到您的 DbContext 中,该类型参数必须是您要注入的对象类型。

你的情况

public class AppManagerDBContext : IdentityDbContext
{
    public AppManagerDBContext(DbContextOptions<AppManagerDBContext> options) : base(options) { }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // ...
    }

    // ...
}

两个错误都很好解释。

您必须将实体的一个或多个属性标记为主键。
如果你愿意,试试

public class UserInfo : IdentityUser
{
    // DatabaseGenerated is optional.
    // Only in case you want to delegate the key generation
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [PersonalData]
    public string Name { get; set; }
    [PersonalData]
    public DateTime DOB { get; set; }
}

或者,如果您想要 none,将实体配置为未加密。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<BmiInformation>().ToTable("BmInformation");
    modelBuilder.Entity<UserInfo>(u =>
    {
        u.HasNoKey();
    });           
}

希望对您有所帮助。