为什么我的 EF Core 查询返回的列表与 SQL Management studio 中的结果不匹配?

问题描述 投票:0回答:1

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>();
} 

有两个问题:

  1. 结果列表包含10条相同数据的记录
  2. 此列表中的第一个元素与 SQL Management Studio 中返回的 SQL 不匹配。 我做错了什么?
c# sql entity-framework
1个回答
0
投票

您的 EF 代码按身份 ID 排序(

b => b.Id
,这是
-1
,因为您的查询中有
-1 as id
),而您的查询按
originaldocid
(
d.id
) 排序。不确定这是否是问题所在,但这是我注意到的第一件事。

© www.soinside.com 2019 - 2024. All rights reserved.