【问题标题】:insert IdentityUser with default values and custom properties fails使用默认值和自定义属性插入 IdentityUser 失败
【发布时间】:2018-12-05 19:07:45
【问题描述】:

我在这里建立了几个帖子:

所以我用自定义属性扩展了我的 IdentityUser;这一切都很好。这些自定义属性在 SQL Server 中被指定为具有默认值,即如果我插入一个新用户,这些自定义属性的默认值应该会弹出,对吧?

不 - 它们以 NULL 值失败(因为它们被指定为 NOT NULL),如果我将它们打开为非 NOT NULL,它们会在此处失败(在 AddClaim 行),

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
    // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

    // Add custom user claims here
    userIdentity.AddClaim(new Claim("companyId", this.companyId.ToString()));

    return userIdentity;
}

因为即使在 mssql = "newcompanyid" 中设置了 companyId 默认值,它也不会从 NULL 设置,因此返回为 NULL。

我在这里错过了什么?

【问题讨论】:

  • “这些自定义道具的默认值应该正确弹出” - 假设这一切都由实体框架 DbContext 支持,那么不。您必须将映射属性更改为 StoreGeneratedPattern 值之一 - 我通常将其更改为 Identity。
  • 在这里暗中拍摄,但只是为了确认: // 在此处添加自定义用户声明 userIdentity.AddClaim(new Claim("companyId", this.groupId.ToString()));... 是这意味着是组 ID 还是公司 ID?
  • @Mitchell - 是的,除了我做了一个类型 - 现在更新了....

标签: asp.net asp.net-mvc asp.net-identity


【解决方案1】:

感谢 tieson
我能够使用这种技术解决这个问题:

http://www.vannevel.net/2015/04/03/how-to-configure-a-custom-identityuser-for-entity-framework/

有以下基础:

所以最后我的代码看起来像:

public class ApplicationUser : IdentityUser
{
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public int companyId { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

        // Add custom user claims here
        userIdentity.AddClaim(new Claim("companyId", this.companyId.ToString()));

        return userIdentity;
    }
}

希望这对其他人有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2017-05-08
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多