IdentityServer 4 Entity Framework ConfigurationDbContext Client.AllowedScopes 和其他非客户端 Table 属性为空

IdentityServer 4 Entity Framework ConfigurationDbContext Client.AllowedScopes and Other Non-Clients Table Properties are Null

我的 .NET Core Startup.cs 文件中有一个数据库初始化方法,它在 MySql 数据库上执行 Entity Framework 数据库初始化并加载客户端、身份资源和 API 从配置文件(C# 代码)到数据库的资源。插入新客户端和更新作为 Clients table 一部分的客户端属性(例如“描述”)一样效果很好。我遇到的问题是位于其他与客户端相关的 table 中的数据,例如 ClientScopesClientGrantTypes 不会返回并填充到 IdentityServer4.EntityFramework.Entities.Client 对象中,因此我无法在代码中将我的配置与数据库进行比较,以添加或删除源代码控制配置文件中已更改的任何属性。

private void InitializeDatabase(IApplicationBuilder app)
{
    using IServiceScope serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope();
    ConfigurationDbContext context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
    context.Database.Migrate();
    foreach (IdentityServer4.Models.Client client in Config.GetClients())
    {
        Client contextClient = context.Clients.FirstOrDefault(p => p.ClientId == client.ClientId);
        if (contextClient == null)
        {
            context.Clients.Add(client.ToEntity());
        }
        else // for simplicity, leaving out any "else if" checks
        {
            Client entity = client.ToEntity();
            contextClient.Description = entity.Description;

            // Get client scopes that were removed from the client configuration and that are in the database
            // Exception (NullReferenceException) thrown because contextClient.AllowedScopes is NULL even though there are values in IdentityDb.ClientScopes, so the following two commands don't function as expected.
            var scopesToBeRemoveFromDb = contextClient.AllowedScopes.Where(p => !entity.AllowedScopes.Exists(x => x.Scope == p.Scope));
            ...
        }
        ...
    }
    ...
}

我是否遗漏了一些东西来确保 context.Clients 调用也能带回这些额外的 table 数据?

您需要使用.Include()来加载相关数据。

https://docs.microsoft.com/en-us/ef/core/querying/related-data