"Where "中可空属性的right join Linq C# lambda表达式 EF Core

问题描述 投票:0回答:1

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

这是代码。

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."
c# linq lambda entity-framework-core expression
1个回答
0
投票

注意到这个错误异常,你就会知道这是由于你的Linq不能被转写造成的,因为你使用的是Queryable,它会调用数据库评估,所以你需要做的是重写查询或使用AsEnumerable()作为客户端评估:。

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

参考资料:https:/docs.microsoft.comen-usefcorequeryingclient-eval。

© www.soinside.com 2019 - 2024. All rights reserved.