首页 > 解决方案 > 如何在 foreach 循环(EF Core 3)中使用 EF.CompileQuery?

问题描述

我有一个类和一个视图模型类。

UserClass 包含大约 30,000 条记录


[Key]
public int UserId { get; set; }

public string UserName { get; set; }

public string Email { get; set; }

public string Password { get; set; }

public string ActiveCode { get; set; }

public bool IsActive { get; set; }

public string UserAvatar { get; set; }

public DateTime RegisterDate { get; set; } = DateTime.Now;

public bool IsDelete { get; set; } = false;

我的视图模型类包含

public string UserName { get; set; }
public string Email { get; set; }
public DateTime RegisterDate { get; set; }

我想像这样运行我的查询

var list=   EF.CompileQuery((TopLearnContext db) =>
                                 db.Users.Select(x=>new InformationUserViewModel()
                                 {
                                     Email = x.Email,
                                     UserName = x.UserName,
                                     RegisterDate = x.RegisterDate
                                 }));
                                 
                                 
         foreach (var item in list)
         {
             
         }

但在运行时出现此错误:

foreach statement cannot operate on variables of type 'Func<TopLearnContext, IEnumerable<InformationUserViewModel>>' because 'Func<TopLearnContext, IEnumerable<InformationUserViewModel>>' does not contain a public instance definition for 'GetEnumerator'   

我的问题是,如何在 EF.CompileQuery 中执行 foreach 循环?

据我所知,EF.CompileQuery 提高了性能,因此我想知道如何在 foreach 中使用它。

标签: entity-framework-core

解决方案


ACompiledQuery没有任何东西可以循环。如果您想要查询的结果,则必须先执行它:

var toLoop = list.Invoke(context, ...)

这将是一个IQueryable可以循环的。


推荐阅读