如何在foreach循环(EF Core 3)中使用EF.CompileQuery?

时间:2019-12-07 22:05:13

标签: entity-framework core

嗨,我有一个类和一个视图模型类

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;

和我的viewmodel类包含

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)
         {

         }

和VS2019在运行时显示此错误:

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中使用它。

2 个答案:

答案 0 :(得分:0)

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

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

这将是一个IQueryable,可以循环播放。

答案 1 :(得分:0)

感谢您的回复,我尝试了,它可以正常工作 却要花费像这种方法一样的时间

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

EF.CompileQuery是否应该具有更快的编译时间?