c# - 只有实现 IAsyncEnumerable 的源才能用于 Entity Framework 异步操作

标签 c# entity-framework asynchronous

我正在使用 EF 6.1.3 和 .NET Framework 4.6.1 实现一个模型。 此模型由 ASPNET 应用程序和 ASPNET CORE 应用程序使用,因此它使用 System.Data.Entity 并且它位于单独的程序集 mymodel.dll 中。

这是模型

using System.Data.Entity;
public partial class MyDbContext : DbContext
{    
        public virtual DbSet<Athlete> Athletes{ get; set; }
}
public partial class Athlete
{
    public Athlete()
    {
    }
    //...
    public string Country { get; set; }
}

我正在开发使用 .NET Framework 4.6 在 aspnet core 中实现的 MVC 应用程序。它引用 EF 6.1.3,以便可以使用该模型。

public class MyViewModel
{
    public IList<Athlete> ItalianAthletes{ get; set; }
}

using Microsoft.EntityFrameworkCore;
//solution: comment the previous line and use instead System.Data.Entity;
public class MyController : Controller
{
    private readonly MyDbContext _context;
    //...
    public IActionResult Index()
    {
       MyViewModel myvm = new MyViewModel();
       var result = _context.Athletes.Where(a=>a.Country=="Italy").ToList();
       myvm.ItalianAthletes = result ;
       return View(myvm);
    }
}

... 并且按预期工作。

现在将 Index 方法更改为异步

public async Task<IActionResult> Index()
{
   MyViewModel myvm = new MyViewModel();
   var result = _context.Athletes.Where(a=>a.Country=="Italy").ToListAsync();
   await result; //at this point an exception is thrown
   //...
}

InvalidOperationException: The source IQueryable doesn't implement IAsyncEnumerable. Only sources that implement IAsyncEnumerable can be used for Entity Framework asynchronous operations.

删除 Where() 子句问题仍然存在,因此问题似乎与 ToListAsync() 有关;

var result = _context.Users.ToListAsync();

仔细阅读异常的文本,我了解到“ToList() 生成的 IQueryable 没有实现 IAsyncEnumerable”,但这对我来说没有意义,因为所有这些行为都是 ToListAsync() 的内部行为;

有人可以帮助我更好地了解幕后发生的事情吗?我该怎么做才能使 ToListAsync() 按预期工作?

提前感谢您的任何评论

最佳答案

如果您使用的是 Entity Framework Core,那么您必须使用此命名空间:

using Microsoft.EntityFrameworkCore;

代替

using System.Data.Entity;

关于c# - 只有实现 IAsyncEnumerable 的源才能用于 Entity Framework 异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39169597/

相关文章:

scala - 如何在 ScalaTest 中使用具有异步规范的夹具上下文对象?

python - Python DBus 异步方法的实现

javascript - 如何识别ajax已提交请求但正在等待响应?

c# - Xunit 为每个新测试创建新的测试类实例(使用 WebDriver 和 C#)

c# - 在 EF 中调用 SaveChanges() 后,将获取的旧记录保留在变量中

c# - 将新实体插入到具有标识主键的上下文中

ASP.NET Core EF6 身份

c# - Environment.GetEnvironmentVariable ("windir") 奇怪的行为

c# - 发布 : "This program might not have installed correctly" 后运行 exe 时出错

c# - 我可以将自定义属性添加到PasswordCredential.Properties 中吗?