如何从dbo.AspNetUsers表中读取数据?

3

我想从Identity表dbo.AspNetUsers中检索数据,但我还没找到如何查询它的方法。

这是我的db-context:

public class ProjectsDbContext : IdentityDbContext<IdentityUser>
{
    public ProjectsDbContext(DbContextOptions<ProjectsDbContext> options) : base(options) { }

    public DbSet<Project> Projects { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        if (modelBuilder == null)
        {
            throw new NullReferenceException();
        }

        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Project>()
            .HasMany(c => c.ChildProjects)
            .WithOne(p => p.ParentProject)
            .HasForeignKey(p => p.ParentProjectId);
    }
}

这是我的User类:

public class User : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

这是我的查询,但它不起作用:

List<User> projectOwners = await db.Users.ToListAsync();

我收到的错误信息是:

无法隐式将类型 'System.Collections.Generic.List<Microsoft.AspNetCore.Identity.IdentityUser>' 转换为 'System.Collections.Generic.List<Projects.Models.User>'

如果我在查询中使用 var 替换 List<User>,则错误消失了,但是我获得的集合不包含我自己定义在 User 类中的任何属性。
如何访问 AspNetUsers,包括我自己在 User 中定义的额外属性?
2个回答

5

使用 EF Core,AspNetUsers 表将被映射到 Users DbSet,因此您可以通过以下方式轻松引用它:

db.Users

如果你想自定义AspNetTable,添加自己的字段,例如FirstName和LastName,那么你需要从IdentityUser派生,如@timur的回答所示,但你仍然可以只使用db.Users引用该表。

请务必更新您的数据上下文文件,我的示例是“public partial class APP_DataContext:IdentityDbContext <IdentityUser>”,您还需要获取更新的NuGet以使用EF Identity。 - AtLeastTheresToast

2

假设您的项目大体上按照标准样板进行设置,我相信您可以像这样转换您身份用户的覆盖类型:

Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
            // pretty standard initialisation so far
            services.AddDbContext<ProjectsDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<User>(options => options.SignIn.RequireConfirmedAccount = false) // this is the key - put your custom User Identity here
                .AddEntityFrameworkStores<ProjectsDbContext>();
        }

ProjectsDbContext.cs

public class User : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    public class ProjectsDbContext: IdentityDbContext<User> // this is your custom User type
    {
        public ProjectsDbContext(DbContextOptions<ProjectsDbContext> options)
            : base(options)
        {
        }
    }

接下来,由于你正在更改数据模型,所以你需要迁移模式:

PM> Add-Migration change_IdentityUser
PM> Update-Database

您会注意到迁移将您的自定义字段添加到表中:

public partial class change_IdentityUser : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<string>(
                name: "FirstName",
                table: "AspNetUsers",
                nullable: true);

            migrationBuilder.AddColumn<string>(
                name: "LastName",
                table: "AspNetUsers",
                nullable: true);
        } 
.......

最后,所有对SignInManager/UserManager和其他辅助类的引用都需要更新为新的泛型类型参数:

_LoginPartial.cshtml

@inject SignInManager<User> SignInManager
@inject UserManager<User> UserManager

这给了我运行时异常“无法将类型为...的对象强制转换为...” - Stian
没问题。我认为你的DbContext应该是ProjectsDbContext : IdentityDbContext<User> - 我会更新答案。 - timur
那岂不意味着我必须更改所有身份视图?它们都引用了“IdentityUser”。 - Stian
我本来希望不必更改视图中的所有类型引用(例如_LoginPartial.cshtml),但我有点理解为什么需要这样做。今天我没有时间尝试,但明天会研究一下。 - Stian
这个解决方案需要你在 Identity Razor 页面和代码后台的许多地方从 IdentityUser 更改为 User。但它非常有效! :) - Stian
显示剩余2条评论

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