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

3
我有这个类。
public class ApplicationUser : IdentityUser
{
   public string Email { get; set; }
   public string ConfirmationToken { get; set; }
   public bool IsConfirmed { get; set; }
   ...
}

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; }
    ....
}

现在,当我尝试使用以下查询语句来查询我的存储库中的Users表时:
var user = _db.Users.SingleOrDefault(u=>u.anyfield);

我认为它的返回类型是IdentityUser而不是ApplicationUser,因为当我在u=>u.时智能提示选项并没有显示来自ApplicationUser 的字段。
我应该怎么做才能使查询Users表返回ApplicationUser类型,并且为什么它给出的返回类型是IdentityUser

你尝试过 _dbContext.Users.OfType<ApplicationUser>().SingleOrDefault... 吗? - Raphaël Althaus
不,我会尝试一下。请稍等一分钟。 - Cybercop
谢谢!那似乎起作用了。我不知道那个。 - Cybercop
另一个猜测,因为使用.OfType不是它应该的方式。(我不需要那样做)- 尝试删除modelBuilder.Entity<IdentityUser>().ToTable("Users");,因为您已将ApplicationUser映射到该表。我的怀疑是第二行某种方式覆盖了第一行,这就是为什么该实体返回IdentityUser而不是ApplicationUser。请尝试一下。 - Marco
@Serv 好的,我会试一下。 - Cybercop
@Serv,如果我删除它,它就不起作用了。 - Cybercop
1个回答

6

由于IdentityDbContext不是您定义的类,而ApplicationUser是您定义的类。您可以创建继承自IdentityUser的ApplicationUser。然后再创建一个继承自IdentityDbContext的上下文。IdentityDbContext公开DbSet。

如果你想要将数据作为ApplicationUser返回,你可以采取以下步骤:

context.Users.OfType<ApplicationUser>();

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

public new DbSet<ApplicationUser> Users { get; set; }

不过我还没有测试过。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接