我正在使用ASP.Net Identity 2和EF6代码首次迁移此项目,我正在努力创建一个表来链接其他3个表。我有以下内容:
棘手的一点是将AspNetUserRoles与Company表相关联,因为用户可以在不同的公司中拥有角色,并且还可以拥有与任何公司无关的角色。理想情况下,我需要的结果表是:
另一个选择是将另一个字段(companyId)添加到AspNetUserRoles表。
如何通过代码优先实现这一点以及它对UserManager和RoleManager有什么影响(我是否需要创建自定义代码?),这有点令人困惑。
非常感谢任何指导。
答案 0 :(得分:0)
根据相同的源代码编写代码自己现在走的假设。
首先,使用mvc(c#)在vs中创建新项目,并在mvc上选择项目类型。
然后,在创建项目之后,您应该更改一些类Identity。
我希望更改在表UserId
中输入Nvarchar(128)
到Bigint
的{{1}}。
第一步到第七步在AspNetUsers
。
第一步:根据以下内容将类IdentityModels.cs
更改为:
IdentityModels.cs
更改为:ApplicationUser : IdentityUser
。
第二步:创建类:
ApplicationUser : IdentityUser<long, CustomUserLogin, CustomUserRole, CustomUserClaim>
第三步:
根据:更改课程
public class CustomUserRole : IdentityUserRole<long> { }
public class CustomUserClaim : IdentityUserClaim<long> { }
public class CustomUserLogin : IdentityUserLogin<long> { }
第四步:根据以下内容更改课程:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, long> manager)
第五步:根据以下内容改变课程:
public class CustomRole : IdentityRole<long, CustomUserRole>
第六步:根据以下内容改变课程:
public class CustomUserStore : UserStore<ApplicationUser, CustomRole, long, CustomUserLogin, CustomUserRole, CustomUserClaim>
第七步:根据以下内容改变课程:
public class CustomRoleStore : RoleStore<CustomRole, long, CustomUserRole>
并根据您的表格字段将以下方法添加到 public class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole, long, CustomUserLogin, CustomUserRole, CustomUserClaim>
:
IdentityModels.cs
在protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//modelBuilder.Entity<CustomUserLogin>()
//.HasKey(r => new { r.UserId })
//.ToTable("tblRoles");
//modelBuilder.Entity<CustomUserLogin>()
// .HasKey(l => new { l.LoginProvider, l.ProviderKey, l.UserId })
// .ToTable("tblMembers");
modelBuilder.Entity<IdentityUser>().HasKey(r => new { r.Id }).ToTable("tblMembers1").Property(p => p.Id).HasColumnName("UserID");
modelBuilder.Entity<ApplicationUser>().HasKey(r => new { r.Id }).ToTable("tblMembers").Property(p => p.Id).HasColumnName("UserID");
modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId }).ToTable("tblRoless");
modelBuilder.Entity<IdentityUserLogin>().HasKey(r => new { r.UserId }).ToTable("tblLogins");
modelBuilder.Entity<IdentityUserClaim>().HasKey(r => new { r.Id }).ToTable("tblUserClaims");
modelBuilder.Entity<IdentityRole>().HasKey(r => new { r.Id }).ToTable("tblRoloess");
}
根据以下内容进行更改
AccountControllers.cs
private bool HasPassword()
{
var user = UserManager.FindById(User.Identity.GetUserId<long>());
if (user != null)
{
return user.PasswordHash != null;
}
return false;
}
public virtual ActionResult RemoveAccountList()
{
var linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId<long>());
ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1;
return PartialView("_RemoveAccountPartial", linkedAccounts);
}
public virtual async Task<ActionResult> Disassociate(string loginProvider, string providerKey)
{
ManageMessageId ? message = null;
IdentityResult result = await UserManager.RemoveLoginAsync(
User.Identity.GetUserId<long>(),
new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<long>());
await SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
else
{
message = ManageMessageId.Error;
}
return RedirectToAction("Manage", new { Message = message });
}
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
AuthenticationManager.SignIn(new AuthenticationProperties()
{ IsPersistent = isPersistent },
await user.GenerateUserIdentityAsync(UserManager));
}
根据以下内容发生变化:
IdentityConfig.cs
然后,在工具菜单的Windows 程序包管理器控制台中编写以下命令以添加迁移:
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
return Task.FromResult(0);
}
}
public class SmsService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your SMS service here to send a text message.
return Task.FromResult(0);
}
}
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser, long>
{
public ApplicationUserManager(IUserStore<ApplicationUser, long> store) : base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(
new CustomUserStore(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser, long>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Register two factor authentication providers. This application uses Phone
// and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug in here.
manager.RegisterTwoFactorProvider("PhoneCode",
new PhoneNumberTokenProvider<ApplicationUser, long>
{
MessageFormat = "Your security code is: {0}"
});
manager.RegisterTwoFactorProvider("EmailCode",
new EmailTokenProvider<ApplicationUser, long>
{
Subject = "Security Code",
BodyFormat = "Your security code is: {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser, long>(
dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
// Configure the application sign-in manager which is used in this application.
}
public class ApplicationSignInManager : SignInManager<ApplicationUser, long>
{
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) : base(userManager, authenticationManager)
{
}
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
{
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
然后:
Enable migrations
根据图像: enter image description here
最好的问候。