我第一次尝试MVC 6,Entity Framework 7和ASP.NET Identity。 我刚刚生成了一个默认项目,我正在根据以下教程更改登录过程以支持租户帐户。
https://www.scottbrady91.com/ASPNET-Identity/Quick-and-Easy-ASPNET-Identity-Multitenancy
问题是,当我尝试更改初始迁移以支持AspNetUsers表上的复合密钥(Id,TenentId)时,它只会失败并显示一般消息。 迁移代码如下。
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
TenantId = table.Column<string>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Email = table.Column<string>(nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
LockoutEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
NormalizedEmail = table.Column<string>(nullable: true),
NormalizedUserName = table.Column<string>(nullable: true),
PasswordHash = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
SecurityStamp = table.Column<string>(nullable: true),
TwoFactorEnabled = table.Column<bool>(nullable: false),
UserName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ApplicationUser", x => new { x.Id, x.TenantId });
});
我也尝试了以下代码,但它也不起作用。
constraints: table =>
{
table.PrimaryKey("PK_ApplicationUser", x => x.Id);
table.PrimaryKey("PK_ApplicationUser", x => x.TenantId);
});
如果我将其保留为非复合键,则迁移将成功执行。
constraints: table =>
{
table.PrimaryKey("PK_ApplicationUser", x => x.Id);
});
我尝试在两个列上定义一个唯一约束,但我无法找到方法。
有没有人对此有任何想法?
答案 0 :(得分:1)
Identity表的任何自定义都需要通过创建Identity模型类的派生类和/或通过从IdentityDbContext
类创建派生类来完成。
但我不会尝试更改Identity表的主键结构。我非常怀疑它会起作用,如果确实如此,那么就没有任何保证它会正常工作。
只是为了让你指出正确的方向,这是我如何修改我的IdentityUser类(AspNetUsers表)。我添加了一些属性来存储从Active Directory检索的数据。
public class ApplicationUser : IdentityUser
{
[Required]
[StringLength(50)]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
public string LastName { get; set; }
[Required]
public bool Active { get; set; }
}
执行此操作需要您从使用上述模型类的IdentityDbContext
类创建派生类。我在我的网站上重命名身份表。
public class MyDbContext : IdentityDbContext<ApplicationUser>
{
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
//Rename the ASP.NET Identity tables.
builder.Entity<ApplicationUser>().ToTable("User");
builder.Entity<IdentityRole>().ToTable("Role");
builder.Entity<ApplicationRole>().ToTable("Role");
builder.Entity<IdentityUserRole<string>>().ToTable("UserRole");
builder.Entity<IdentityUserLogin<string>>().ToTable("UserLogin");
builder.Entity<IdentityUserClaim<string>>().ToTable("UserClaim");
builder.Entity<IdentityRoleClaim<string>>().ToTable("UserRoleClaim");
}
}
然后在Startup.cs中的ConfigureServices()方法
//Add Identity services.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<MyDbContext>()
.AddDefaultTokenProviders();