繁体   English   中英

使用ASP.Net Identity EntityFramwork到ID列设置为UniqueIdentifier的现有AspNetUsers表

[英]Using ASP.Net Identity EntityFramwork to Existing AspNetUsers table with ID Column set to UniqueIdentifier

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

在执行呼叫以获取用户时,出现错误:

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

有一种方法可以在代码中设置Id属性,因为我无法修改数据库中的column属性。

这是我的代码段:

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变量上展开并检查Users属性时看到错误。

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

使主键的类型对用户和角色可扩展

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

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

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

其中int是用户ID的类型。 如果要使用自定义的UserLoginUserRoleUserClaim (默认情况下,它们的ID也是UserClaim ,因此您可能也想这样做),则必须添加自定义继承的类:

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<int, UserLogin, UserRole, UserClaim> (如上所述),而int是id类型。 因此,用两个词来说,基本思想是使用您自己的实现继承默认的Identity类型,并在Identity使用其默认类型的地方使用它们。 这是可以的做法。 对于您的情况,我建议UniqueIdentifier是一些自定义类型,因此您必须使用此类型而不是int例如您提供的示例 ):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM