4

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

创建数据库和表时,我只想将用户 ID 的类型更改为 uniqueidentifier 而不是 nvarchar(128)。我尝试在 OnModelCreating 覆盖中使用 .HasColumnType("uniqueidentifier") 进行此操作...但它会引发错误。

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

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

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

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

4

2 回答 2

2

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

我相信您不仅需要实施IUserStore,而且在我看来,您需要自己的UserStore实施,因为UserStore<TUser>仅限于IdentityUser.

如果我是正确的,这意味着您至少需要实现IUserStoreIUserPasswordStore和。IUserSecurityStampStoreIUserLoginStore

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

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

于 2013-11-11T19:24:16.843 回答
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);
        }
    }
于 2013-11-11T20:00:25.013 回答