Linq查询未返回预期的结果数

时间:2017-10-09 14:44:29

标签: c# sql-server entity-framework linq

我有两种数据模型:

public class SSC {
    public int Id { get; set; }
    public string Name { get; set; }
    //other irrelevent properties removed for brevity
    public virtual ICollection<SpecReference> SpecReferences { get; set; }
}

public class SpecReference {
    public int Id { get; set; }
    public string Name { get; set; }
    //other irrelevent properties removed for brevity
    public virtual ICollection<SSC> SSCs { get; set; }
}

我在我的数据上下文中定义了两者之间的多对多关系:

modelBuilder.Entity<SSC>().HasMany(a => a.SpecReferences)
    .WithMany(b => b.SSCs)
    .Map(c => {
        c.MapRightKey("SpecReference_Id");
        c.MapLeftKey("SSC_Id");
        c.ToTable("SpecReferenceSSCs");
    });

在我的网站的某一点上,我有一个高级搜索页面,用户可以通过SSC中的任何字段或连接到SSC的任何导航字段的组合搜索SSC。除非用户指定SpecReference,否则每次搜索都有效。查询代码(缩写为仅显示相关代码)是:

var query = _dbContext.SSCs.Where(x => !x.IsDeleted);

if (designSpecificationIds != null && designSpecificationIds.Any()) {
    var designSpecificationIdsHash = new HashSet<int>(designSpecificationIds);
    query = query.Where(x => x.SpecReferences.Any(s => designSpecificationIdsHash.Contains(s.Id)));
}

其中designSpecificationIds是从Web表单传递的整数数组。

当我运行应用程序并逐步执行搜索代码时,从查询生成的SQL是:

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[SSCId] AS [SSCId], 
[Extent1].[Name] AS [Name], 
[Extent1].[SystemFunction] AS [SystemFunction], 
[Extent1].[Remarks] AS [Remarks], 
[Extent1].[IsSystem] AS [IsSystem], 
[Extent1].[IsGrouping] AS [IsGrouping], 
[Extent1].[IsConfiguration] AS [IsConfiguration], 
[Extent1].[FieldTag] AS [FieldTag], 
[Extent1].[ParentId] AS [ParentId], 
[Extent1].[IPlantParentId] AS [IPlantParentId], 
[Extent1].[BuildingId] AS [BuildingId], 
[Extent1].[IsOperable] AS [IsOperable], 
[Extent1].[IsAvailable] AS [IsAvailable], 
[Extent1].[DutyAreaId] AS [DutyAreaId], 
[Extent1].[IsDeleted] AS [IsDeleted]
FROM [dbo].[SSCs] AS [Extent1]
WHERE ([Extent1].[IsDeleted] <> 1) AND ( EXISTS (SELECT 
    1 AS [C1]
    FROM [dbo].[SpecReferenceSSCs] AS [Extent2]
    WHERE ([Extent1].[Id] = [Extent2].[SSC_Id]) AND ([Extent2].[SpecReference_Id] IN (4))
))

如果我对数据库运行此SQL,我会得到一个我期望的结果。但是,当我检查Linq查询并尝试枚举结果时,我得到“枚举没有结果”。 Linq查询生成的SQL如何返回与查询本身不同的结果?

编辑: 要返回值,我使用ExpressMapper将Model转换为DTO。转换只是:

return Mapper.Map<IEnumerable<SSC>, IEnumerable<SSCIndexDto>>(query);

DTO是:

public class SSCIndexDto {
    public int Id { get; set; }
    public string Name { get; set; }
    //Other properties omitted for brevity
    public List<SpecReferenceIndexDto> SpecReferences { get; set; }
}

同样,映射似乎对所有其他属性都正常工作,包括与SpecReferences完全相同的导航属性。这是查询本身没有返回任何数据。

0 个答案:

没有答案