如何解决IdentityServer 4实体框架配置DbContext Client.AllowedScopes和其他非客户端表属性为Null
.NET Core Startup.cs文件中有一个数据库初始化方法,该方法在MySql数据库上进行Entity Framework数据库初始化,并将客户端,身份资源和API资源从配置文件(C#代码)加载到数据库中。插入新客户端和更新Clients
表(例如“ description”)中的客户端属性的工作一样好。我遇到的问题是位于其他与客户相关的表中的数据(如ClientScopes
或ClientGrantTypes
)不会返回并填充在IdentityServer4.EntityFramework.Entities.Client
对象中,所以我可以t将我的配置与代码中的数据库进行比较,以便添加或删除源控制的配置文件中已更改的所有属性。
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
调用将这些附加表的数据也带回来的东西?
解决方法
您需要使用.include()加载相关数据。
https://docs.microsoft.com/en-us/ef/core/querying/related-data
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。