需要将Asp.Net Identity(RTM)用户ID从nvarchar(128)更改为uniqueidentifier

时间:2013-11-11 17:14:22

标签: c# asp.net asp.net-membership asp.net-identity

使用Asp.Net Identity 1.0(RTM版本)。默认实现创建一个AspNetUsers表。 Id列类型为nvarchar(128)。

在创建数据库和表时,我只想将User Id的类型更改为uniqueidentifier而不是nvarchar(128)。我在OnModelCreating覆盖中使用.HasColumnType(“uniqueidentifier”)尝试了这个...但是它会抛出错误。

微软表示这很容易......但我倾向于不同意......

  

http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity

     

由于您控制数据库架构,因此更改等常见任务   表名或更改主键的数据类型很简单。

因此,根据他们非常简短且完全非技术性的文档,这似乎是一项常见的任务,更改主键的数据类型......但似乎没有任何简单的说明。请帮忙。

2 个答案:

答案 0 :(得分:2)

来自ASP.NET团队的Hao Kung已在StackOverflow发布了您需要实现自己的IUserStore,但他正在努力使1.1版本更容易。

我相信您不仅需要实施IUserStore,因为UserStore仅限于UserStore<TUser>,因此您似乎需要自己的IdentityUser实施。< / p>

如果我是正确的,这意味着您至少需要实施IUserStoreIUserPasswordStoreIUserSecurityStampStoreIUserLoginStore

这是14种方法,但大多数方法都非常直接实现。请注意,这不是UserStore<TUser>的完全替代,只是您需要支持默认模板中AccountController使用的部分。

我在GitHub上有一个项目,我自己尝试了这个项目,即我实现了一个使用MongoDb而不是EntityFramework进行持久化的UserStore。

答案 1 :(得分:1)

如果您更新到最新的夜间位,您可以试用新的1.1-alpha1 api,这应该使现在更容易:这是插入Guids而不是字符串应该是什么样的例子

    public class GuidRole : IdentityRole<Guid, GuidUserRole> { 
        public GuidRole() {
            Id = Guid.NewGuid();
        }
        public GuidRole(string name) : this() { Name = name; }
    }
    public class GuidUserRole : IdentityUserRole<Guid> { }
    public class GuidUserClaim : IdentityUserClaim<Guid> { }
    public class GuidUserLogin : IdentityUserLogin<Guid> { }

    public class GuidUser : IdentityUser<Guid, GuidUserLogin, GuidUserRole, GuidUserClaim> {
        public GuidUser() {
            Id = Guid.NewGuid();
        }
        public GuidUser(string name) : this() { UserName = name; }
    }

    private class GuidUserContext : IdentityDbContext<GuidUser, GuidRole, Guid, GuidUserLogin, GuidUserRole, GuidUserClaim> { }
    private class GuidUserStore : UserStore<GuidUser, GuidRole, Guid, GuidUserLogin, GuidUserRole, GuidUserClaim> {
        public GuidUserStore(DbContext context)
            : base(context) {
        }
    }
    private class GuidRoleStore : RoleStore<GuidRole, Guid, GuidUserRole> {
        public GuidRoleStore(DbContext context)
            : base(context) {
        }
    }

    [TestMethod]
    public async Task CustomUserGuidKeyTest() {
        var manager = new UserManager<GuidUser, Guid>(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);
        }
    }