Ale*_*akh 5 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()
Run Code Online (Sandbox Code Playgroud)
当我尝试在支持ASP.NET Core 2.0 EntityFramework的应用程序中执行相同的代码时,我的应用程序将冻结,并且永远不会返回结果。
我尝试了一些变体,但一旦将子查询作为初始查询的一部分执行,所有变体就会挂起:
另一个子查询变体(也会在执行时挂起):
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 }
Run Code Online (Sandbox Code Playgroud)
另一个子查询变体(也挂在执行中):
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() }
Run Code Online (Sandbox Code Playgroud)
左外部联接的另一个变体(也挂在执行时):
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}
Run Code Online (Sandbox Code Playgroud)
下面的代码有效,但是很明显,子查询的执行被推迟了,一旦我们尝试访问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.
}
}
Run Code Online (Sandbox Code Playgroud)
如何执行子查询并获取实体列表,其中每个实体分配了使用子查询接收的子实体列表?
小智 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();
Run Code Online (Sandbox Code Playgroud)