【问题标题】:Why is the return type IdentityUser and not ApplicationUser?为什么返回类型是 IdentityUser 而不是 ApplicationUser?
【发布时间】:2014-04-09 03:22:49
【问题描述】:

我有这门课

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=&gt;u. 智能感知选项时,不会显示来自ApplicationUser 的字段

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

【问题讨论】:

  • 你试过了吗_dbContext.Users.OfType&lt;ApplicationUser&gt;().SingleOrDefault...
  • 不,会试一试。只需一分钟
  • 谢谢!这似乎有效。不知道。
  • 另一个猜测,因为使用.OfType 不是它应该的方式。 (我不需要这样做) - 尝试删除 modelBuilder.Entity&lt;IdentityUser&gt;().ToTable("Users");,因为您已经将 ApplicationUser 映射到该表。我的怀疑是,第二行以某种方式覆盖了第一行,这就是为什么该实体返回IdentityUser 而不是ApplicationUser。请试一试。
  • @Serv ok 会试一试

标签: c# asp.net-mvc entity-framework asp.net-mvc-5 asp.net-identity


【解决方案1】:

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

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

context.Users.OfType<ApplicationUser>();

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

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

不过我还没有测试过。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-22
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 2020-07-24
    相关资源
    最近更新 更多