EF核心排除多列为空或为空的情况

时间:2019-09-06 13:38:27

标签: c# linq ef-core-2.0

我有一个名为ControlActivityChangeLog的SQL Server表。该表具有列CurrentValueNewValue,它们都是可空的nvarchars。如何查询所有ControlActivityChangeLogs,但不包括CurrentValue和NewValue为null或为空的结果。如果CurrentValue为null或为空,而NewValue不是,那么我需要该记录。

我尝试将其添加到以下查询中,但最终未返回任何结果:

!x.ControlActivityChangeLogs.Any(y => string.IsNullOrEmpty(y.CurrentValue) && string.IsNullOrEmpty(y.NewValue))

这是我的qry:

var qry = _context.ControlActivities
        .Include(x => x.ControlActivityChangeLogs)
        .Include(x => x.Company)
        .Where(x => 
            !x.IsDeleted && 
            !x.IsArchived && 
            !x.ControlActivityChangeLogs.Any(y => string.IsNullOrEmpty(y.CurrentValue) && string.IsNullOrEmpty(y.NewValue)))
        .AsQueryable();


    **OTHER COLUMN FILTERS HERE**


    var results = await qry.Select(x => new ModifiedCAModel
            {
                **List Of Columns**,
                Changes = x.ControlActivityChangeLogs
                    .Where(y => y => y.ControlActivityIssueId == null && y.ControlActivityTestId == null)
                    .OrderByDescending(y => y.ChangedDate)
                    .ToList()
            }).ToListAsync();

2 个答案:

答案 0 :(得分:1)

the below should be able to translate to SQL correctly

var qry = _(context.ControlActivities
    .Include(x => x.ControlActivityChangeLogs)
    .Include(x => x.Company)
    .Where(x => !x.IsDeleted 
             && !x.IsArchived 
             && x.ControlActivityChangeLogs.CurrentValue != null 
             && x.ControlActivityChangeLogs.CurrentValue != ""
             && x.ControlActivityChangeLogs.NewValue != null 
             && x.ControlActivityChangeLogs.NewValue != ""
    ).AsQueryable();

您应该检查正在执行什么SQL!

这可以获取,但是将记录添加到ef。

答案 1 :(得分:1)

WhereAny条件适用于包括,因此您需要

  

排除结果,其中CurrentValue NewValue 为空或为空

include 结果,其中CurrentValue NewValue 为空或为空 < / p>

即代替

!x.ControlActivityChangeLogs.Any(y => string.IsNullOrEmpty(y.CurrentValue) && string.IsNullOrEmpty(y.NewValue)))

您需要

x.ControlActivityChangeLogs.Any(y => !string.IsNullOrEmpty(y.CurrentValue) || !string.IsNullOrEmpty(y.NewValue)))