在我的 .NET Core 3 WebAPI 项目中,我有以下简单的方法调用:
[HttpGet("ViewerRoles")]
public IAsyncEnumerable<ViewerRole> GetViewList() {
using var db = new MpaContext();
return db.ViewerRoles.AsAsyncEnumerable();
}
这向我抛出了一个 ObjectDisposeException。AsAsyncEnumerable()
相对较新,我找不到任何适当的示例来说明如何在这种情况下使用它。我应该删除using
关键字和实体框架数据库连接神奇地自行处置?还是还有别的伎俩?
你有两个选择。要么枚举IAsyncEnumerable
在你的里面GetViewList
method:
[HttpGet("ViewerRoles")]
public async IAsyncEnumerable<ViewerRole> GetViewList()
{
using var db = new MpaContext();
await foreach (var item in db.ViewerRoles.AsAsyncEnumerable().ConfigureAwait(false))
{
yield return item;
}
}
...或安装System.Interactive.Async封装并使用静态AsyncEnumerableEx.Using
method:
[HttpGet("ViewerRoles")]
public IAsyncEnumerable<ViewerRole> GetViewList()
{
return AsyncEnumerableEx.Using(() => new MpaContext(),
db => db.ViewerRoles.AsAsyncEnumerable());
}
这是该人的签名AsyncEnumerableEx.Using
method:
public static IAsyncEnumerable<TSource> Using<TSource, TResource>(
Func<TResource> resourceFactory,
Func<TResource, IAsyncEnumerable<TSource>> enumerableFactory)
where TResource : IDisposable;
不幸的是,似乎没有该库的在线文档。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)