asp.net-core-2.1 – 如何在asp.net Core 2.1.1中为IdentityUser创建自定义字段

前端之家收集整理的这篇文章主要介绍了asp.net-core-2.1 – 如何在asp.net Core 2.1.1中为IdentityUser创建自定义字段前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我创建了一个扩展“IdentityUser”类的Model.
public class ApplicationUser : IdentityUser
{
    public string FirstName_TXT { get; set; }
    public string LastName_TXT { get; set; }
}

在定义dbcontext时,我确保包含IdentityDbContext以及ApplicationUser Reference.

//initial DB Configuration
public class DbContext : IdentityDbContext<ApplicationUser>
{
    //Users References Articles
    //Articles Automaticalled gets create
    public DbSet<ContactRequest> ContactRequests { get; set; }
    public DbSet<Class> Classes { get; set; }

    public DbContext()
    {

    }

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

    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UsesqlServer(@"Server=.\sqlEXPRESS;Database=DBNAME;Trusted_Connection=True;");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

当我尝试使用控制台应用程序中的其他字段创建数据库时,出现以下错误.

class Program
{
    static void Main(string[] args)
    {

        using (var ctx = new DbContext())
        {
            ctx.Database.EnsureCreatedAsync();

            ctx.SaveChanges();

        }
    }
}

System.InvalidOperationException: ‘A key cannot be configured on ‘ApplicationUser’ because it is a derived type. The key must be configured on the root type ‘IdentityUser’. If you did not intend for ‘IdentityUser’ to be included in the model,ensure that it is not included in a DbSet property on your context,referenced in a configuration call to ModelBuilder,or referenced from a navigation property on a type that is included in the model.’

不确定我错过了什么.任何建议将不胜感激.

解决方法

关键属性不能被设计忽略. IdentityUser具有默认密钥属性Id.
您的ApplicationUser类未指定其Id字段的类型.我把我的代码
public class ApplicationUser : IdentityUser<string>
{
    public string FirstName_TXT { get; set; }
    public string LastName_TXT { get; set; }
}

您可以使用整数类型Id密钥属性,为此使用IdentityUser< int>

猜你在找的.NET Core相关文章