具有异步任务的ObjectContext ExecuteFunction

时间:2017-01-13 08:40:18

标签: asynchronous asp.net-web-api entity-framework-6 task

将实体框架6与asp.net webapi一起使用,并使用存储过程进行映射, 如何将ObjectContext执行方法转换为异步任务?

1 个答案:

答案 0 :(得分:1)

作为ExecuteFunction的替代方法,您可以使用以下构造,它将为您提供异步执行:

var results = from game in PlayersGames
    group game by game.Player into group
    select new { Player = group.Key, TotalScore = group.Sum(g => g.Score), Indexes = String.Join(",", group.Select(g => g.Index)) };

或:

Task<SomeResult[]> results = ctx.Database.SqlQuery<SomeResult>("EXEC sp_myproc {0}, {1}, {2}", p1, p2, p3).ToArrayAsync();

如果您需要使用ExecuteFunction方法,可以试试这个:

SomeResult[] results = await ctx.Database.SqlQuery<SomeResult>("EXEC sp_myproc {0}, {1}, {2}", p1, p2, p3).ToArrayAsync();

这就是说,值得一提的是,如果您决定使用ExecuteFunction方法,实际的SQL语句将在IDbAsyncEnumerable<SomeResult> enumerable = this.ExecuteFunction<SomeResult>("sp_myproc", p1, p2, p3) as IDbAsyncEnumerable<SomeResult>; IDbAsyncEnumerator<SomeResult> enumerator = enumerable.GetAsyncEnumerator(); while (await enumerator.MoveNextAsync(CancellationToken.None)) { SomeResult res = enumerator.Current; ... } 行上运行,而不是在枚举结果时。