c# - LINQ .All() - 总是返回 true
问题描述
设置
- ASP.NET 核心 3.1
- EF 核心 3.1
我正在编写一个 LINQ 语句来从 DB 中检索一些实体,但遇到了问题。这是声明:
var Tag = "this is an input parameter";
location.SRID = 4326;
var posts = await _context.Posts
.Include(p => p.Location)
.Include(p => p.Event)
.Include(p => p.Repeatable)
.Include(p => p.Voucher)
.Include(p => p.Tags)
.ThenInclude(pt => pt.Tag)
.Where(p => p.ActiveFlag == 1 &&
p.Location.Location.IsWithinDistance(location, radius * 1000) &&
p.EventTime > today &&
p.Tags.All(pt => pt.Tag.TagName.Contains(Tag.ToLower()))) // always true
.AsNoTracking().ToListAsync();
问题是它p.Tags.All(condition)
总是为所有人返回 true。看起来它忽略了这个条件。我什至尝试TrueForAll()
改用,但这在 EF Core 3.1 中根本不起作用,它返回:
...无法翻译。要么以可翻译的形式重写查询,要么通过插入对 AsEnumerable()... 的调用显式切换到客户端评估。
这是缩小的 Post 模型及其与 PostTags 和 Tags 的关系:
public class Post
{
public int Id { get; set; }
public virtual List<PostTags>? Tags { get; set; }
}
public class PostTags
{
public virtual Tag Tag { get; set; }
public int TagId { get; set; }
public virtual Post Post { get; set; }
public int PostId { get; set; }
}
public class Tag
{
public int Id { get; set; }
public string TagName { get; set; }
public virtual IEnumerable<PostTags>? Posts { get; set; }
}