我正在尝试使用aspnetcore身份进行多租户,但是我在尝试修改“UserNameIndex”唯一索引以包含tenantid时遇到了麻烦。
我可以看到我要修改的索引如下(这是来自Microsoft.AspNetCore.Identity.EntityFrameworkCore / IdentityDbContext.cs)
__str__
以下是我的dbcontext
的摘录class Test(object):
def __str__(self):
return 'Test str'
__repr__ = __str__
当我添加迁移时,这绝对没有影响 - 但是如果我重命名索引,它会创建迁移!是否无法覆盖索引?
答案 0 :(得分:1)
我有同样的问题,我设法解决这个问题的唯一方法是完全覆盖OnModelCreating方法。这很不幸,因为我想要修改的总配置非常少。
public class MyContext : IdentityDbContext<Customer, CustomerRole, int>
{
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Customer>(b =>
{
b.HasKey(u => u.Id);
b.HasIndex(u => new { u.NormalizedUserName, u.TenantId}).HasName("UserNameIndex").IsUnique();
b.HasIndex(u => new { u.NormalizedEmail, u.TenantId}).HasName("EmailIndex");
b.ToTable("AspNetUsers");
b.Property(u => u.ConcurrencyStamp).IsConcurrencyToken();
b.Property(u => u.UserName).HasMaxLength(256);
b.Property(u => u.NormalizedUserName).HasMaxLength(256);
b.Property(u => u.Email).HasMaxLength(256);
b.Property(u => u.NormalizedEmail).HasMaxLength(256);
b.HasMany((u => u.Claims)).WithOne().HasForeignKey(uc => uc.UserId).IsRequired();
b.HasMany((u => u.Logins)).WithOne().HasForeignKey(ul => ul.UserId).IsRequired();
b.HasMany((u => u.Roles)).WithOne().HasForeignKey(ur => ur.UserId).IsRequired();
});
builder.Entity<CustomerRole>(b =>
{
b.HasKey(r => r.Id);
b.HasIndex(r => new { r.NormalizedName, r.TenantId}).HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
b.Property(r => r.ConcurrencyStamp).IsConcurrencyToken();
b.Property(u => u.Name).HasMaxLength(256);
b.Property(u => u.NormalizedName).HasMaxLength(256);
b.HasMany(r => r.Users).WithOne().HasForeignKey(ur => ur.RoleId).IsRequired();
b.HasMany(r => r.Claims).WithOne().HasForeignKey(rc => rc.RoleId).IsRequired();
});
builder.Entity<IdentityUserClaim<int>>(b =>
{
b.HasKey(uc => uc.Id);
b.ToTable("AspNetUserClaims");
});
builder.Entity<IdentityRoleClaim<int>>(b =>
{
b.HasKey(rc => rc.Id);
b.ToTable("AspNetRoleClaims");
});
builder.Entity<IdentityUserRole<int>>(b =>
{
b.HasKey(r => new
{
r.UserId, r.RoleId
});
b.ToTable("AspNetUserRoles");
});
builder.Entity<IdentityUserLogin<int>>(b =>
{
b.HasKey(l => new
{
l.LoginProvider, l.ProviderKey
});
b.ToTable("AspNetUserLogins");
});
builder.Entity<IdentityUserToken<int>>(b =>
{
b.HasKey(l => new
{
l.UserId, l.LoginProvider, l.Name
});
b.ToTable("AspNetUserTokens");
});
}
}
不要忘记更新/重新生成迁移。
请注意我每个租户也有角色,所以我也更改了RoleNameIndex。如果您不想这样做,只需将该行更改为:
b.HasIndex(r => r.NormalizedName).HasName("RoleNameIndex");