实体框架.NET Core 2.0查询在执行子查询时挂起执行

时间:2017-08-21 20:38:42

标签: c# sql entity-framework entity-framework-6 entity-framework-core

使用常规版本的EF 6.x,我可以通过以下查询轻松完成子查询:

var q = from u in db.User
        let actions = from ua in db.UserActions
                      where ua.UserId == u.Id && ua.Approved
                      select ua
        where u.Active
        select new { User = u, Actions = actions.ToList() }

var result = await q.ToListAsync()

当我尝试在我的ASP.NET Core 2.0 EntityFramework驱动的应用程序中执行相同的代码时,我的应用程序只是冻结并且永远不会返回结果。

我尝试了一些变体,但是一旦子查询作为初始查询的一部分执行,它们都会挂起:

  1. 子查询(与上面的一些变体相同)
  2. 左外连接
  3. 另一个子查询变体(在执行时也会挂起):

    var q = from u in db.User
            let actions = (from ua in db.UserActions
                          where ua.UserId == u.Id && ua.Approved
                          select ua).ToList()
            where u.Active
            select new { User = u, Actions = actions }
    

    又一个子查询变体(也在执行时挂起):

    var q = from u in db.User
            let actions = db.UserActions.Where(ua => ua.UserId == u.Id && ua.Approved)
            where u.Active
            select new { User = u, Actions = actions.ToList() }
    

    左外连接的另一个变体(也在执行时挂起):

    var forUserId = "test";
    var q = from u in db.User
            join ua in db.UserActions on u.Id equals ua.UserId into actions
            from ua in action.DefaultIfEmpty()
            where u.Active
            select new { User = u, Actions = ua}
    

    以下代码有效,但显然,子查询执行被推迟,一旦我们尝试访问Action属性,它就会启动另一个查询:

    var q = from u in db.User
            let actions = from ua in db.UserActions
                          where ua.UserId == u.Id && ua.Approved
                          select ua
            where u.Active
            select new { User = u, Actions = actions }
    
    var result = await q.ToListAsync()
    foreach (var r in result)
    {
         foreach(var a in r.Actions)
         {
              // extra database requests is executed for each result row
              // .. process action.
         }
    }
    

    如何执行子查询并获取实体列表,其中每个实体分配了子实体列表,使用子查询接收?

1 个答案:

答案 0 :(得分:0)

我不确定。但是,你可以试试' .ToList()'。

 var q = (from u in db.User
            join ua in db.UserActions on u.Id equals ua.UserId into actions
            from ua in action.DefaultIfEmpty()
            where u.Active
            select new {u,ua}).ToList();