我第一次尝试使用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);
});
我试图在两列上定义一个唯一约束,但是我找不到解决方法。
有人对此有任何想法吗?
身份表的任何自定义都需要通过创建身份模型类的派生类和/或通过从IdentityDbContext
该类创建派生类来完成。
但是我不会尝试更改身份表的主键结构。我严重怀疑这种做法是否会奏效,如果能奏效,则无法保证它会正常工作。
为了使您指向正确的方向,这是我修改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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句