如何让Job表关联ASP.NET Core Identity的AspNetUser表而非CustomIdentity表
解决ASP.NET Core Identity多上下文关联用户表的问题
让JobDBContext复用AuthDbContext的用户实体配置
别在JobDBContext里单独配置CustomIdentity,直接复用AuthDbContext里的配置逻辑。先写一个独立的CustomIdentityConfiguration配置类,强制指定表名为AspNetUsers:public class CustomIdentityConfiguration : IEntityTypeConfiguration<CustomIdentity> { public void Configure(EntityTypeBuilder<CustomIdentity> builder) { builder.ToTable("AspNetUsers"); // 和Identity生成的表名保持一致 // 此处可添加CustomIdentity扩展字段的配置 } }然后在JobDBContext的
OnModelCreating方法中引入该配置,再配置Job与CustomIdentity的关联:public class JobDBContext : DbContext { public JobDBContext(DbContextOptions<JobDBContext> options) : base(options) { } public DbSet<Job> Jobs { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new CustomIdentityConfiguration()); // 配置Job和用户的关联关系 modelBuilder.Entity<Job>() .HasOne<CustomIdentity>(j => j.User) .WithMany(u => u.Jobs) .HasForeignKey(j => j.UserId) .HasPrincipalKey(u => u.Id); } }禁止JobDBContext生成用户表
注册上下文时,仅对AuthDbContext执行迁移操作,避免JobDBContext重复生成用户相关表:// 注册两个数据库上下文 builder.Services.AddDbContext<AuthDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("AuthConnection"))); builder.Services.AddDbContext<JobDBContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("JobConnection"))); // 只迁移AuthDbContext对应的表 using (var scope = app.Services.CreateScope()) { var authContext = scope.ServiceProvider.GetRequiredService<AuthDbContext>(); authContext.Database.Migrate(); }显式指定外键约束的目标表
配置Job的外键时,手动指定约束名称和关联表,避免EF Core自动推断错误:modelBuilder.Entity<Job>() .HasOne(j => j.User) .WithMany() .HasForeignKey(j => j.UserId) .HasPrincipalKey(u => u.Id) .HasConstraintName("FK_Jobs_AspNetUsers_UserId") // 明确指向AspNetUsers表 .OnDelete(DeleteBehavior.Cascade);可选方案:共用数据库连接
如果业务允许Auth和Job模块共用同一个数据库,直接让两个上下文使用相同的连接字符串,EF Core会自动识别已存在的AspNetUsers表,不会生成新的CustomIdentity表。
内容的提问来源于stack exchange,提问作者Lakshmi Sureshan
相关产品推荐
相关产品推荐

