如何首先使用EF6代码创建AspNetUserRoles和其他一些表之间的关系?

问题描述:

我正在使用ASP.Net身份2和EF6代码第一次迁移为这个项目,我努力创建一个表来链接3个其他表。我有以下几点:如何首先使用EF6代码创建AspNetUserRoles和其他一些表之间的关系?

  • 公司
  • ApplicationUser(AspNetUsers)
  • ApplicationRole(AspNetRoles)
  • AspNetUserRoles

棘手位是与公司表涉及的AspNetUserRoles,因为用户可以在不同的公司中担任角色,也可以具有与任何公司无关的角色。因此,理想的结果表我需要的是这样的:

  • CompanyUserRoles(companyId,UserRoleId [这不是角色ID]),甚至(companyId,角色ID,用户ID)

另一种选择是将将另一个字段(companyId)添加到AspNetUserRoles表。

这有点令人困惑,我怎么才能用代码实现这一点,以及它对UserManager和RoleManager有什么影响(我是否需要创建自定义的?)。

任何指导将不胜感激。

根据相同的源代码,现在就自己编写代码。 首先,您使用mvc(c#)创建新项目并在mvc上选择项目类型。 然后,创建项目后,你应该改变一些类的标识。 我想更改为UserId已在Nvarchar(128)BigintAspNetUsers。 第一步到第七步在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 cha NGE根据:

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变化根据:

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 

Then:

Add-migration TestMig 

根据图像: enter image description here

最好的问候。

+0

请投票给我的答案。 :)) – MojtabaNava

+0

感谢您的回答,但不幸的是它没有回复我的问题。 – Fabio

+0

您应该在您的项目中使用代码。 :)) – MojtabaNava