Azure AD使用Visual Studio违反了PRIMARY KEY约束

本文关键字:PRIMARY KEY 约束 AD 使用 Visual Studio Azure | 更新日期: 2023-09-27 18:13:21

我使用visual studio 2013创建了一个MVC应用程序,并连接到我们的Azure AD租户,没有问题。今天早上我突然收到错误:

违反PRIMARY KEY约束'PK_dbo.Tenants'。无法在对象'dbo.Tenants'中插入重复键。重复键值为(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX)。语句已被终止。

租户密钥是我们组织的租户Id。

这个应用程序已经开发了一个多月了,直到今天早上还没有出现任何问题。

在创建应用程序时生成的函数中出现错误:

public static void RefreshKeys(string metadataLocation)
    {
        IssuingAuthority issuingAuthority = ValidatingIssuerNameRegistry.GetIssuingAuthority(metadataLocation);
        bool newKeys = false;
        foreach (string thumbprint in issuingAuthority.Thumbprints)
        {
            if (!ContainsKey(thumbprint))
            {
                newKeys = true;
                break;
            }
        }
        if (newKeys)
        {
            using (TenantDbContext context = new TenantDbContext())
            {
                context.IssuingAuthorityKeys.RemoveRange(context.IssuingAuthorityKeys);
                foreach (string thumbprint in issuingAuthority.Thumbprints)
                {
                    context.IssuingAuthorityKeys.Add(new IssuingAuthorityKey { Id = thumbprint });
                }
                foreach (string issuer in issuingAuthority.Issuers)
                {
                    context.Tenants.Add(new Tenant { Id = issuer.TrimEnd('/').Split('/').Last() });
                }
                context.SaveChanges();
            }
        }
    }

Azure AD使用Visual Studio违反了PRIMARY KEY约束

您的代码正在创建新的租户,而没有首先检查它们是否已经存在。据猜测,系统以前从未处理过与多个IssuingAuthority关联的租户ID。

要立即解决这个问题,检查租户是否已经存在,如下所示(注意我还没有测试过这段代码):

public static void RefreshKeys(string metadataLocation)
{
    IssuingAuthority issuingAuthority = ValidatingIssuerNameRegistry.GetIssuingAuthority(metadataLocation);
    bool newKeys = false;
    foreach (string thumbprint in issuingAuthority.Thumbprints)
    {
        if (!ContainsKey(thumbprint))
        {
            newKeys = true;
            break;
        }
    }
    if (newKeys)
    {
        using (TenantDbContext context = new TenantDbContext())
        {
            context.IssuingAuthorityKeys.RemoveRange(context.IssuingAuthorityKeys);
            foreach (string thumbprint in issuingAuthority.Thumbprints)
            {
                context.IssuingAuthorityKeys.Add(new IssuingAuthorityKey { Id = thumbprint });
            }
            // Get the Tenant IDs we have been supplied with
            IEnumerable<string> tenantIds = issuingAuthority.Issuers.Select(i => i.TrimEnd('/').Split('/').Last());
            // Exclude any that already exist in the database
            List<string> newTenantIds = tenantIds.Except(context.Tenants.Select(t => t.Id)).ToList();
            // Add only the new Tenant instances to the database
            foreach (string tenantId in newTenantIds)
            {
                context.Tenants.Add(new Tenant { Id = tenantId });
            }
            context.SaveChanges();
        }
    }
}