Nub 与 Ef 核心中的 SQL 查询斗争。 我有一个试图用 SQL 查询填充的 DBSet。我不知道查询是否重要,但这里是:
select top 10
2 as docstorageid,
d.ID as originaldocid,
df.id as originalfileid,
c.id as custid,
u.id as userid,
-1 as id,
df.Page as PageId,
df.FileName as FilePath
from documents d
inner join DocumentFiles df on df.Documents_ID = d.id
inner join users u on u.login_id = d.UploadedBy_User_ID
inner join customers c on c.id = u.Customers_ID
where df.FileTypes_ID = 2 and substring (df.FileName, 1,4) = 'arti'
and df.id not in (select originalfileid from documenttemplatefiles)
order by d.id desc
它在 sql 管理器中执行得很好,产生 10 个唯一记录。 我的 EF 核心代码是:
int count =10;
try
{
List <DocTemplateFile> rval = _context.DocumentTemplateFiles.FromSql(
$@"select distinct
2 as docstorageid,
d.ID as originaldocid,
df.id as originalfileid,
c.id as custid,
u.id as userid,
-1 as id,
df.Page as PageId,
df.FileName as FilePath
from documents d
inner join DocumentFiles df on df.Documents_ID = d.id
inner join users u on u.login_id = d.UploadedBy_User_ID
inner join customers c on c.id = u.Customers_ID
where df.FileTypes_ID = 2 and substring(df.FileName, 1,4) = 'arti'
and df.id not in (select originalfileid from documenttemplatefiles)"
)
.OrderByDescending(b => b.Id)
.Take(count)
.Distinct()
.ToList();
return rval;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return new List<DocTemplateFile>();
}
有两个问题:
您的 EF 代码按身份 ID 排序(
b => b.Id
,这是 -1
,因为您的查询中有 -1 as id
),而您的查询按 originaldocid
(d.id
) 排序。不确定这是否是问题所在,但这是我注意到的第一件事。