"Where" in nullable 属性 of right join Linq C# lambda expression EF Core

"Where" in nullable property of right join Linq C# lambda expression EF Core

我有一个查询要列出一组名为 Transaction with children 的实体。当尝试应用 where 来过滤子项中的道具时,它会抛出 Linq 无效操作。 (EF 核心)

代码如下:

var query = DataContext.Transactions
                .Select(x => new Transaction
                {
                    Id = x.Id,
                    TotalAmount = x.TotalAmount,
                    CreatedAt = x.CreatedAt,
                    TransactionState = x.TransactionState == null ? null :
                    new TransactionState
                    {
                        Id = x.TransactionState.Id,
                        Name = x.TransactionState.Name
                    },
                    Beneficiary = x.Beneficiary == null ? null :
                    new Beneficiary
                    {
                        Id = x.Beneficiary.Id,
                        DocumentNumber = x.Beneficiary.DocumentNumber
                    }
                })
                .AsNoTracking()
                .AsQueryable();

            if (!filter.IsNullEmtpyOrWhiteSpace()) // Own Property
            {
                // This is the line where apply where in prop
                query = query.Where(x => x.Beneficiary != null && x.Beneficiary.DocumentNumber.Contains(filter));
            }

            var count = query.Count();

            if (take > 0) query = query.Skip(skip).Take(take);

            return new ListAndCountDto<Transaction>
            {
                Data = query.ToList(),
                Count = count
            };

这是错误异常:

"The LINQ expression 'DbSet<Transaction>\n    
.LeftJoin(\n outer: DbSet<Beneficiary>, \n        
inner: t => EF.Property<Nullable<int>>(t, 
\"BeneficiaryId\"), \n outerKeySelector: b => EF.Property<Nullable<int>>(b, \"Id\"), \n 
innerKeySelector: (o, i) => new TransparentIdentifier<Transaction, Beneficiary>(\n 
Outer = o, \n Inner = i\n ))\n .Where(t => EF.Property<Nullable<int>>(t.Inner, \"Id\") == null ? 
null : new Beneficiary{ \n Id = t.Inner.Id, \n DocumentNumber = t.Inner.DocumentNumber \n    }\n  
!= null && EF.Property<Nullable<int>>(t.Inner, \"Id\") == null ? null : new Beneficiary{ \n       
Id = t.Inner.Id, \n        DocumentNumber = t.Inner.DocumentNumber \n    }\n    
.DocumentNumber.Contains(__filter_0))' could not be translated. Either rewrite the query in a 
form that can be translated, or switch to client evaluation explicitly by inserting a call to 
either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See 
https://go.microsoft.com/fwlink/?linkid=2101038 for more information."

注意错误异常,你就会知道这是你的linq无法翻译造成的。 当您使用 Queryable 时,它​​将调用数据库评估。 所以你需要做的是重写查询或使用 AsEnumerable() 作为客户端评估:

var query = DataContext.Transactions.AsEnumerable()
            .Select()...

参考:https://docs.microsoft.com/en-us/ef/core/querying/client-eval