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

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

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. intellisense 选项不显示来自 ApplicationUser

的字段

enter image description here

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

最佳答案

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

如果您希望数据作为 ApplicationUser 返回,您可以执行以下操作:

context.Users.OfType<ApplicationUser>();

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

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

虽然我还没有测试过。

关于c# - 为什么返回类型是 IdentityUser 而不是 ApplicationUser?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22225365/

相关文章:

entity-framework - 首先从数据库模型自动更新代码,这可能吗?

c# - 比较字典中值之间的差异

c# - 无法将生成的带有私钥的证书导出到 .NET 4.0/4.5 中的字节数组

c# - 从 X509Certificate 对象导出私钥

c# - 如何使用 asp.net core 2 测试具有属性的方法?

asp.net-mvc - 临时数据持久化

c# - Entity Framework 6 自动迁移定期在生产服务器上重建表

javascript - 不能有图表的实体是什么概念?

c# - 流利的 NHibernate : mapping a dictionary of lists

entity-framework - 如何从实体对象获取对上级对象的引用