如何使用 EF.CompileQuery in foreach loop (EF Core 3)?



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

用户类包含大约 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 中执行 foreach 循环。编译查询?

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

CompiledQuery

没有任何要循环的内容。如果你想要查询的结果,它必须首先执行:

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

这将是一个可以循环的IQueryable

感谢您的回复,我尝试了一下,它有效 但它需要的时间与这种方法一样多

var list = db.Users.Select(x=>new InformationUserViewModel()
{
Email = x.Email,
UserName = x.UserName,
RegisterDate = x.RegisterDate
}).toList();

不应该 EF。CompileQuery必须有更快的编译时间吗?

最新更新