Asp.net Identity 系列之 怎樣修改Microsoft.AspNet.Identity.EntityFramework.IdentityUser 的 Id 字段的數據類型


    這篇博客我們來學習如何將AspNetUsers 表的Id 字段 的類型由nvarchar(128) 改為Int 並且子增長

   

1、為什么要修改

  如果你運行過 Asp.net mvc 示例項目,你好會發現 AspNetUsers 表的Id是Nvarchar(128) 類型,值為GUID,不可否認使用GUID來做主鍵進行主外鍵關聯會增加數據安全性(個人看法),但是非常不利於查詢,可讀性不夠,因此我們嘗試着去改為Int類型。

 先看一下修改后的效果:

 

 2、修改前分析

   查看數據庫結構我們知道要修改的表有這樣四張表 ,他們涉及到UserId,RoleId.具體結構這里不做分析。

1 SELECT * FROM dbo.AspNetUsers
2 SELECT * FROM dbo.AspNetRoles
3 SELECT * FROM dbo.AspNetUserRoles
4 SELECT * FROM dbo.AspNetUserLogins

3、如何修改代碼實現功能

如果你認真研究Asp.Net Identity 你會發現其擴展性非常好.

我們新建一個Mvc4,5項目,打開Models-->IdentityModels.cs .查看到ApplicationUser class(和用戶相關的類)繼承了IdentityUser.cs (位於Microsoft.Asp.Net.Identity.EntityFramework.dll) 反編譯后源碼如下:

 1 namespace Microsoft.AspNet.Identity.EntityFramework
 2 {
 3     using Microsoft.AspNet.Identity;
 4     using System;
 5     
 6     public class IdentityUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser, IUser<string>
 7     {
 8         public IdentityUser()
 9         {
10             this.Id = Guid.NewGuid().ToString();
11         }
12         
13         public IdentityUser(string userName) : this()
14         {
15             this.UserName = userName;
16         }
17     }
18 }

 觀察 IdentityUser.cs 它有繼承了IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser, IUser<string>這個泛型,所以我們也需要有對應的Int類型的 IdentityUserLogin, IdentityUserRole, IdentityUserClaim泛型類。

如下所示:

 1     public class IntRole : IdentityRole<int, IntUserRole>
 2     {
 3         public IntRole()
 4         {
 5 
 6         }
 7         public IntRole(string name) : this() { Name = name; }
 8     }
 9     public class IntUserRole : IdentityUserRole<int> { }
10     public class IntUserClaim : IdentityUserClaim<int> {}
11     public class IntUserLogin : IdentityUserLogin<int> { }
12 
13     public class IntUserContext : IdentityDbContext<ApplicationUser, IntRole, int, IntUserLogin, IntUserRole, IntUserClaim>
14     {
15         public IntUserContext()
16             : base("DefaultConnection")
17         {
18 
19         }
20     }

 然后我們修改Application.cs

 

 1     public class ApplicationUser : IdentityUser<int, IntUserLogin, IntUserRole, IntUserClaim>
 2     {
 3         public ApplicationUser() { }
 4         public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
 5         {
 6             // 請注意,authenticationType 必須與 CookieAuthenticationOptions.AuthenticationType 中定義的相應項匹配
 7             var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
 8             // 在此處添加自定義用戶聲明
 9             return userIdentity;
10         }
11         public ApplicationUser(string name) : this() { UserName = name; }
12     }

由於我們對Application.cs做了修改,還需要查看Identityfig.cs並作相應的修改。修改后的代碼如下:

 public class ApplicationUserManager : UserManager<ApplicationUser, int>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser, int> store)
            : base(store)
        {

        }

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new IntUserStore(context.Get<ApplicationDbContext>()));

// 配置用戶名的驗證邏輯 manager.UserValidator = new UserValidator<ApplicationUser, int>(manager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true, }; // 配置密碼的驗證邏輯 manager.PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = false, RequireDigit = false, RequireLowercase = false, RequireUppercase = false, }; // 配置用戶鎖定默認值 manager.UserLockoutEnabledByDefault = true; manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); manager.MaxFailedAccessAttemptsBeforeLockout = 5; // 注冊雙重身份驗證提供程序。此應用程序使用手機和電子郵件作為接收用於驗證用戶的代碼的一個步驟 // 你可以編寫自己的提供程序並將其插入到此處。 manager.RegisterTwoFactorProvider("電話代碼", new PhoneNumberTokenProvider<ApplicationUser, int> { MessageFormat = "你的安全代碼是 {0}" }); manager.RegisterTwoFactorProvider("電子郵件代碼", new EmailTokenProvider<ApplicationUser, int> { Subject = "安全代碼", BodyFormat = "你的安全代碼是 {0}" }); manager.EmailService = new EmailService(); manager.SmsService = new SmsService(); var dataProtectionProvider = options.DataProtectionProvider; if (dataProtectionProvider != null) { manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, int>(dataProtectionProvider.Create("ASP.NET Identity")); } return manager; } }

主要對以上紅色部分做了修改.主要代碼就在這里了,如果Rebuild Solition 會出現很多錯誤,不要驚慌,慢慢找找原因來修改

 可能需要修改的部分

  由於將string--->int的數據轉換,慢慢尋找,會發現有很多,ManagerController.cs比較多等等。

 如果想要查看效果還需要將數據表涉及到UserId,RoleId有原來的Nvarchar(128) 改為Int,並設置子增長.

源碼點擊這里 下載

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM