为什么返回类型为IdentityUser而不是ApplicationUser?

Cyb*_*cop 3 c# asp.net-mvc entity-framework asp.net-mvc-5 asp.net-identity

我有这堂课

public class ApplicationUser : IdentityUser
{
   public string Email { get; set; }
   public string ConfirmationToken { get; set; }
   public bool IsConfirmed { get; set; }
   ...
}
Run Code Online (Sandbox Code Playgroud)

DbContext类中,这就是我所做的

public partial class PickerDbContext : IdentityDbContext
{
    public PickerDbContext():base("DefaultConnection")
    {
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<ApplicationUser>().ToTable("Users");
        modelBuilder.Entity<IdentityUser>().ToTable("Users");
        modelBuilder.Entity<IdentityRole>().ToTable("Roles");
    }
    //public DbSet<License> Licenses { get; set; }
    ....
}
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试Users使用类似的查询数据库中的表时

var user = _db.Users.SingleOrDefault(u=>u.anyfield);
Run Code Online (Sandbox Code Playgroud)

我认为它具有返回类型,IdentityUser而不是ApplicationUser因为当我执行u=>u.intellisense选项时,不会显示来自ApplicationUser

在此处输入图片说明

我应该怎么做才能查询Users表的返回ApplicationUser类型,为什么给我返回类型为IdentityUser

Dis*_*ile 5

因为IdentityDbContext不是您定义的类,而ApplicationUser是您确实定义的类。您创建从IdentityUser继承的ApplicationUser。您创建一个从IdentityDbContext继承的上下文。IdentityDbContext公开DbSet。

如果您希望数据以ApplicationUser的身份返回,则可以执行以下操作:

context.Users.OfType<ApplicationUser>();
Run Code Online (Sandbox Code Playgroud)

您也可以在自定义DbContext中(未验证)执行此操作:

public new DbSet<ApplicationUser> Users { get; set; }
Run Code Online (Sandbox Code Playgroud)

我还没有测试过。