Identity change GUID to int

后端 未结 3 788
天涯浪人
天涯浪人 2020-12-03 04:02

How does one change the PK column of the AspNetUser table from a guid to int data type? This should now be possible with the latest

3条回答
  •  我在风中等你
    2020-12-03 04:33

    have a look at this answer by hao-kung in this post

    So if you want int ids, you need to create your own POCO IUser class and implement your IUserStore for your custom IUser class in the 1.0 RTM release.

    This is something we didn't have time to support, but I'm looking into making this easy(ier) in 1.1 right now. Hopefully something will be available in the nightly builds soon.

    Updated with 1.1-alpha1 example: How to get nightly builts

    If you update to the latest nightly bits, you can try out the new 1.1-alpha1 apis which should make this easier now: Here's what plugging in Guids instead of strings should look like for example

    public class GuidRole : IdentityRole { 
        public GuidRole() {
            Id = Guid.NewGuid();
        }
        public GuidRole(string name) : this() { Name = name; }
    }
    public class GuidUserRole : IdentityUserRole { }
    public class GuidUserClaim : IdentityUserClaim { }
    public class GuidUserLogin : IdentityUserLogin { }
    
    public class GuidUser : IdentityUser {
        public GuidUser() {
            Id = Guid.NewGuid();
        }
        public GuidUser(string name) : this() { UserName = name; }
    }
    
    private class GuidUserContext : IdentityDbContext { }
    private class GuidUserStore : UserStore {
        public GuidUserStore(DbContext context)
            : base(context) {
        }
    }
    private class GuidRoleStore : RoleStore {
        public GuidRoleStore(DbContext context)
            : base(context) {
        }
    }
    
    [TestMethod]
    public async Task CustomUserGuidKeyTest() {
        var manager = new UserManager(new GuidUserStore(new GuidUserContext()));
        GuidUser[] users = {
            new GuidUser() { UserName = "test" },
            new GuidUser() { UserName = "test1" }, 
            new GuidUser() { UserName = "test2" },
            new GuidUser() { UserName = "test3" }
            };
        foreach (var user in users) {
            UnitTestHelper.IsSuccess(await manager.CreateAsync(user));
        }
        foreach (var user in users) {
            var u = await manager.FindByIdAsync(user.Id);
            Assert.IsNotNull(u);
            Assert.AreEqual(u.UserName, user.UserName);
        }
    }
    

提交回复
热议问题