我有一个有效的SQL查询,如下所示。我想创建一个等效的Linq查询。没有太大的成功。
assemblies/except
select u.Id as userId, u.CustomerId, a.Id as appId, a.Created as appCreated
from EO_AppUsers u
left join EO_Policies p on (u.Id = p.AppUser_Id)
CROSS APPLY (
select TOP 1 id, created, AppUser_Id
from EO_Applications d
WHERE d.AppUser_id = u.id
order by Created desc ) a
CREATE TABLE [dbo].[EO_AppUsers] (
[Id] NVARCHAR (128) NOT NULL
CREATE TABLE [dbo].[EO_Policies] (
[Id] NVARCHAR (128) NOT NULL,
[AppUser_Id] NVARCHAR (128) NULL,
CREATE TABLE [dbo].[EO_Applications] (
[Id] NVARCHAR (128) NOT NULL,
[Created] DATETIME2 (7) NOT NULL,
[AppUser_Id] NVARCHAR (128) NULL,
有EO_AppUsers
个,零个或多个EO_Policie
。
SQL会创建一份包含所有EO_Applications
和相关EO_AppUsers
以及最新/最新EO_Policies
以下句柄返回EO_AppUsers和EO_Policies但缺少EO_Applications。它需要上面SQL查询中的EO_Applications
。
CROSS APPLY
答案 0 :(得分:0)
您可以尝试此linq查询。
from u in EO_AppUsers
join p in EO_Policies on u.Id equals p.AppUser_Id into pl
from lp in pl.DefaultIfEmpty()
from a in EO_Applications.Where(d => d.AppUser_Id == u.Id)
.OrderByDescending(d => d.Created)
.Take(1)
.DefaultIfEmpty()
select new { userId = u.Id,
u.CustomerId,
appId = a.Id,
appCreated = a.Created,
polId = lp.Id
}