内部实体框架上下文和外部实体之间有什么区别?

时间:2018-09-17 07:54:36

标签: c# async-await entity-framework-6

我正在尝试在C#中以异步方式运行SQL存储过程。我找到了两种选择,我想了解两者之间的区别:

在退出using语句之前,我必须等待,否则上下文将被处置:

private async Task<List<Currency>> Test1Async()
{
    using (var dc = new LandmarkEntities())
    {
        return await Task.Run(() =>
        {
            return dc.get_currencies()
            .Select(x => new Currency
            {
                ExchangeRate = x.exchange_rate,
                Mnemonic = x.mnemonic,
            })
            .ToList();
        });
    }
}

或者我返回一个正在运行的异步任务,该任务包含将在其他地方等待的实体框架上下文:

private Task<List<Currency>> Test2Async()
{
    return Task.Run(() =>
    {
        using (var dc = new LandmarkEntities())
        {
            return dc
                .get_currencies()
                .Select(x => new Currency
                {
                    ExchangeRate = x.exchange_rate,
                    Mnemonic = x.mnemonic,
                })
                .ToList();
        }
    });
}

由于get_currencies()是存储过程.ToListAsync();,因此无法使用。

1 个答案:

答案 0 :(得分:2)

您可以使用.ToListAsync();

private async Task<List<Currency>> Test2Async()
{
    using (var dc = new LandmarkEntities())
    {
        return await dc
            .get_currencies()
            .Select(x => new Currency
            {
                ExchangeRate = x.exchange_rate,
                Mnemonic = x.mnemonic,
            })
            .ToListAsync();
    }
}