【问题标题】:What are the differences between awaiting inside entity framework context and outside?等待内部实体框架上下文和外部有什么区别?
【发布时间】:2018-09-17 17:32:17
【问题描述】:

我正在尝试在 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();不能使用。

【问题讨论】:

  • get_currencies() 是如何定义的?这是你写的函数吗?如果可以,可以发一下吗?
  • 是SQL中定义的存储过程

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


【解决方案1】:

你可以使用.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();
    }
}

【讨论】:

  • 这是我在查询表时所做的,但是似乎不可能对存储过程做同样的事情
  • 本页:entityframeworktutorial.net/efcore/… 建议使用.FromSQL() 而不是您正在使用的函数样式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
  • 2022-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多