如果指定了(与 null 不同),我想按
EquipmentEntity
过滤 Type
列表。该类型是一个可为空的字符串。
要求:
public class GetEquipmentsQuery : IQuery<List<EquipmentDto>> {
public string? Name { get; set; }
public double? Price { get; set; }
public string? Type { get; set; }
}
过滤:
var equipments = await session
.Query<EquipmentEntity>()
.Where(a => (request.Type == null || a.Type == request.Type))
.ToListAsync(cancellationToken);
如果
Type
属性等于 null,则 equipments
是一个空列表。如果 Type
属性有一个值,并且存在一个 EquipmentEntity
其 Type
属性具有该值,则它会包含在返回元素的列表中。
我对这种情况有疑问:
var equipments = await session
.Query<EquipmentEntity>()
.Where(a => request.Type == null)
.ToListAsync(cancellationToken);
我测试了过滤如何在简化的条件下工作。虽然
request.Type == null
是真的,但由于某种原因 equipments
是空的。
我使用非常相似的过滤没有这个问题:
var equipments = await session
.Query<EquipmentEntity>()
.Where(a => (request.Price == null || a.Price <= request.Price))
.ToListAsync(cancellationToken);
在这种情况下,如果
Price
属性等于 null,则不会影响过滤并接收正确的列表。我在这里注意到的唯一区别是 Price
属性是一个可为空的双精度值,而 Type
属性是一个可为空的字符串。
如何制作
Where
以便在 Type
中给定的 request
属性为空时正确过滤?
目前,这对我有用:
using var session = _context.Store.OpenAsyncSession();
var query = session.Query<EquipmentEntity>();
if (request.Name != null) {
query = query.Search(a => a.Name, $"*{request.Name}*");
}
if (request.Price != null) {
query = query.Where(a => a.Price <= request.Price);
}
if (request.Type != null) {
query = query.Where(a => a.Type == request.Type);
}
var equipments= await query.ToListAsync(cancellationToken);
return _mapper.Map<List<EquipmentDto>>(equipments);
当我知道
request
字段不同于 null 时,我只会添加更多过滤器。这避免了过滤器 Where(a => (request.Type == null || a.Type == request.Type))
的问题,因为对齐到特定值会按预期过滤列表。
但是,这是一种解决方法,我想了解为什么以前的方法返回空列表。