【问题标题】:Using ASP.Net Identity EntityFramwork to Existing AspNetUsers table with ID Column set to UniqueIdentifier使用 ASP.Net Identity EntityFramwork 将 ID 列设置为 UniqueIdentifier 的现有 AspNetUsers 表
【发布时间】:2015-01-09 18:14:22
【问题描述】:

我正在使用 Nuget 包 Microsoft.AspNet.Identity.EntityFramework 并连接到现有 SQL Server 数据库,其中 AspNetUsers 表 ID 列设置为 UniqueIdentifier。

在执行获取用户的调用时,我收到一个错误:

“IdentityUser`4”上的“Id”属性无法设置为“System.Guid”值。您必须将此属性设置为“System.String”类型的非空值。

有没有办法在代码中设置 Id 属性,因为我无法修改数据库上的列属性。

这是我的代码 sn-ps:

AuthProvider.cs

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
  public override async Task GrantCredentials(OAuthGrantResourceOwnerCredentialsContext context)
  {
    using(Repository _repo = new Repository())
    {
      IdentityUser user = await _repo.FindUser(context.UName, context.PWord);
      if(user == null)
      {
        // User Not Found / Invalid UName or PWord.
      }
    }
  }
}

Repository.cs

public class Repository : IDisposable
{
  private AppContext _ctx;
  private UserManager<IdentityUser> _usrMgr;

  public Repository()
  {
    _ctx = new AppContext();
    _usrMgr = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
  }

  public async Task<IdentityUser> FindUser(string uName, string pWord)
  {
    // Setting the breakpoint here in this line below: 
    IdentityUser usr = await _usrMgr.FindAsync(uName, pWord);
    return user;
  }
}

在我在 Repository.cs 上设置的断点上,当我展开 _usrMgr 变量并检查用户属性时,我看到了错误。

更新: 我在这里找到了一些信息(在标题部分):

Make the Type of Primary Key Be Extensible for Users and Roles

但我不确定如何正确实施。我需要添加一个新课程吗?在我的理解中,那里的实现相当模糊。

【问题讨论】:

    标签: c# asp.net-identity


    【解决方案1】:

    实际上,是的,您必须实现自己的IdentityUser 类。默认情况下,Identity Framework IdentityUser id 的类型为 string,这并不总是可以接受的。因此,您可以执行以下操作:

    public sealed class User : IdentityUser<int, UserLogin, UserRole, UserClaim>
    

    int 是用户 ID 的类型。如果你想使用自定义的 UserLoginUserRoleUserClaim(默认情况下它们的 id 也是 stings,所以你可能也想这样做),那么你必须添加自定义继承类:

    public class UserRole : IdentityUserRole<int> { } //int is id type
    public class UserClaim : IdentityUserClaim<int> { } //int is id type
    public class UserLogin : IdentityUserLogin<int> { } //int is id type
    

    接下来你要做的是使用你的自定义实体类,由 Identity 提供,管理器(如 UserManagerSignInManager):

    public class ApplicationUserManager : UserManager<User, int> {}
    public class ApplicationSignInManager : SignInManager<User, int> {}
    

    其中User 类型是您的自定义User : IdentityUser&lt;int, UserLogin, UserRole, UserClaim&gt;(如上所述),int 是 id 类型。因此,简而言之,基本思想是用您自己的实现继承默认的 Identity 类型,并在 Identity 使用它的默认类型的地方使用它们。这是可以的做法。在你的情况下,我建议UniqueIdentifier 是一些自定义类型,所以你必须使用这种类型而不是int(比如in example you provided):

    public sealed class User : IdentityUser<UniqueIdentifier, UserLogin, UserRole, UserClaim>
    

    【讨论】:

      猜你喜欢
      • 2014-10-22
      • 2019-03-01
      • 2019-09-01
      • 2013-11-23
      • 1970-01-01
      • 2014-05-14
      • 1970-01-01
      • 2022-06-14
      • 2014-06-28
      相关资源
      最近更新 更多