问题描述
我编写了一个简单的控制台应用程序来从 OpenIddict 服务器获取所有应用程序客户端。我尝试了所有的可能性并得到了语法错误。代码如下。我在 Github 中没有找到任何示例,并发现一些过时的示例(2017)现在不再相关。请帮忙
public static async Task<bool> test()
{
var services = CreateServices();
var provider = services.BuildServiceProvider();
var scope = provider.CreateScope();
var context = scope.ServiceProvider.GetrequiredService<CustomDbContext>();
await context.Database.EnsureCreatedAsync();
var manager = scope.ServiceProvider.GetrequiredService<IOpenIddictApplicationManager>();
var result = await manager.FindByClientIdAsync("TestApp"); // It Works
IQueryable<OpenIddictEntityFrameworkCoreApplication> _applicationsQuery = Enumerable.Empty<OpenIddictEntityFrameworkCoreApplication>().AsQueryable();
_applicationsQuery.Where(apps => apps.ClientId != "");
var clients = manager.ListAsync<Func<OpenIddictEntityFrameworkCoreApplication>>(_applicationsQuery); //Compiler Error
return (result != null);
}
private static IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddDbContext<CustomDbContext>(opts =>
{
opts.UsesqlServer(
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString,b => b.MigrationsAssembly("Program"));
opts.USEOpenIddict();
});
services.AddOpenIddict() // Register the OpenIddict core components.
.AddCore(options =>
{
// Configure OpenIddict to use the Entity Framework Core stores and models.
// Note: call ReplaceDefaultEntities() to replace the default OpenIddict entities.
options.UseEntityFrameworkCore()
.UseDbContext<CustomDbContext>();
// Enable Quartz.NET integration.
options.UseQuartz();
});
return services;
}
解决方法
ListAsync()
返回一个 IAsyncEnumerable<T>
集合,因此您可以使用 await foreach
来迭代集合:
await foreach (var application in manager.ListAsync())
{
Console.WriteLine(await manager.GetClientIdAsync(application));
}
您还可以引用 System.Linq.Async
包并使用异步 LINQ 扩展。例如,您可以通过以下方式检索所有现有应用程序的所有客户端标识符:
var identifiers = await manager.ListAsync()
.SelectAwait(application => manager.GetClientIdAsync(application))
.ToListAsync();