我试图以最有效的方式将集合选择到不可变的数组中。
我还想明确结果集的意图是只读/不变/不跟踪。
var someCollection = await _dataContext
.Set<someType>()
.AsNoTracking()
.ToArrayAsync();我可以这样做,然后转换为不变,但这似乎是疯狂的。
var someImmutableCollection = someCollection
.ToImmutableArray();我也可以这么做:
var someCollection = _dataContext
.Set<someType>()
.AsNoTracking()
.ToImmutableArray();但这不是async。
没有ToImmutableArrayAsync()的原因吗?
或者,是否有更好的方法使用async从efcore获取不可变数组?
发布于 2020-10-20 03:38:13
我可以这样做,然后转换为不变,但这似乎是疯狂的。 var someImmutableCollection = someCollection .ToImmutableArray();
疯了吗?不是很多。让我们来看看源代码
public static async Task<TSource[]> ToArrayAsync<TSource>(
[NotNull] this IQueryable<TSource> source,
CancellationToken cancellationToken = default)
=> (await source.ToListAsync(cancellationToken).ConfigureAwait(false))
.ToArray(); // anti-climax好吧,那里没发生什么魔法。
只需创建您自己的扩展
public class MySuperExtensions
{
public static async Task<ImmutableArray<TSource>> ToImmutableArrayAsync<TSource>(
[NotNull] this IQueryable<TSource> source,
CancellationToken cancellationToken = default)
=> (await source.ToListAsync(cancellationToken).ConfigureAwait(false))
.ToImmutableArray(); // yehaa
}避免了危机,解决了问题。
或者更有效地节省额外的分配和IAsyncStateMachine实现
public static async Task<ImmutableArray<TSource>> ToImmutableArrayAsync<TSource>(
[NotNull] this IQueryable<TSource> source,
CancellationToken cancellationToken = default)
{
var builder = ImmutableArray.CreateBuilder<TSource>();
await foreach (var element in source.AsAsyncEnumerable().WithCancellation(cancellationToken))
builder.Add(element);
return builder.ToImmutable();
}https://stackoverflow.com/questions/64438061
复制相似问题