Asp.net Identity 系列之 怎樣修改Microsoft.AspNet.Identity.EntityFramework.IdentityUser 的 Id 欄位的資料類型

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   ar   os   使用   sp   

    這篇部落格我們來學習如何將AspNetUsers 表的Id 欄位 的類型由nvarchar(128) 改為Int 並且子增長

   

1、為什麼要修改

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

 先看一下修改後的效果:

 

 2、修改前分析

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

1 SELECT * FROM dbo.AspNetUsers2 SELECT * FROM dbo.AspNetRoles3 SELECT * FROM dbo.AspNetUserRoles4 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,並設定子增長.

源碼點擊這裡 下載

 

Asp.net Identity 系列之 怎樣修改Microsoft.AspNet.Identity.EntityFramework.IdentityUser 的 Id 欄位的資料類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.